﻿ Find if two given rectangles are overlapping or not Common Job Interview Questions and Answers

# Find if two given rectangles are overlapping or not

There are two rectangles defined by corner points LowerRight and UpperLeft. The task is to write a function which would check if two given rectangles overlap or not. (Solution in Java).

Was asked this question for Microsoft v- interview SDET position. Jan 2010.

Example:

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) &&
)}

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