Answers and Comments


User Avatar
Written by CommonInterview


Initially it looks like very hard problem and from looking on many possible variations it might look even harder.

The key to notice is that the actual test needed is to check if any of Rect1 corners are inside Rect2 and vice versa. In other words those two rectangle will not overlap if rectangle Rect1 is above Rect2 or below Rect2 or left from Rect2 or right from Rect2.

If any of those conditions are true rectangle don’t overlap… Just four checks !

bool IsOverlap(Rect R1, Rect R2)
{
return ((R1.LR.y <= R2.UL.y)
(R1.LR.x >= R2.UL.x) &&
(R1.UL.x <= R2.LR.x) &&
(R1.UL.y >= R2.LR.y) &&
)}


User Avatar
Written by orthotope


This is not an answer, but I disagree with CommonInterview that "the actual
test needed is to check if any of Rect1 corners are inside Rect2 and vice
versa." For example, suppose that two rectangles are arranged like a cross.
The rectangles overlap, but none of the corners lie withing the other
rectangle.


Saved Stories

Sponsored Categories





100 Common Interview Questions, audio book