Rectangle Overlap
Given two rectangles, find if the given two rectangles overlap or not.
Note that a rectangle can be represented by two coordinates, top left and bottom right. So mainly we are given following four coordinates.
l1: Top Left coordinate of first rectangle.
r1: Bottom Right coordinate of first rectangle.
l2: Top Left coordinate of second rectangle.
r2: Bottom Right coordinate of second rectangle.
Solution:
Since only top left and bottom right point are given, we can consider only overlapping situations when two rectangles are overlapping when one is one the left and the other is on the right; or one is on top and the other is on the bottom;
/**
* Definition for a point.
* class Point {
* public int x, y;
* public Point() { x = 0; y = 0; }
* public Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
/**
* @param l1 top-left coordinate of first rectangle
* @param r1 bottom-right coordinate of first rectangle
* @param l2 top-left coordinate of second rectangle
* @param r2 bottom-right coordinate of second rectangle
* @return true if they are overlap or false
*/
public boolean doOverlap(Point l1, Point r1, Point l2, Point r2) {
if (l1.x > r2.x || l2.x > r1.x) {
return false;
}
if (l1.y < r2.y || l2.y < r1.y) {
return false;
}
return true;
}
}