Rectangle Overlap - Problem

An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.

Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.

Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.

Input & Output

Example 1 — Overlapping Rectangles
$ Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]
Output: true
💡 Note: Rectangle 1 spans from (0,0) to (2,2) and Rectangle 2 spans from (1,1) to (3,3). They overlap in the region from (1,1) to (2,2), which has positive area.
Example 2 — Non-Overlapping Rectangles
$ Input: rec1 = [0,0,1,1], rec2 = [2,2,3,3]
Output: false
💡 Note: Rectangle 1 is at (0,0)-(1,1) and Rectangle 2 is at (2,2)-(3,3). They are completely separate with no overlapping area.
Example 3 — Touching Edges
$ Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1]
Output: false
💡 Note: The rectangles share an edge but do not overlap. Touching at edges or corners doesn't count as overlapping since the intersection area is zero.

Constraints

  • rec1.length == 4
  • rec2.length == 4
  • -109 ≤ rec1[i], rec2[i] ≤ 109
  • rec1[0] ≤ rec1[2] and rec1[1] ≤ rec1[3] (valid rectangle)
  • rec2[0] ≤ rec2[2] and rec2[1] ≤ rec2[3] (valid rectangle)

Visualization

Tap to expand
Rectangle Overlap INPUT rec1 rec2 0 1 2 3 0 1 2 3 rec1 = [0, 0, 2, 2] rec2 = [1, 1, 3, 3] Overlap Area ALGORITHM STEPS (Non-Overlap Conditions) 1 Check Left Separation rec1[2] <= rec2[0] ? 2 <= 1? NO 2 Check Right Separation rec1[0] >= rec2[2] ? 0 >= 3? NO 3 Check Bottom Separation rec1[3] <= rec2[1] ? 2 <= 1? NO 4 Check Top Separation rec1[1] >= rec2[3] ? 0 >= 3? NO Conclusion: None of the non-overlap conditions are true --> Rectangles OVERLAP FINAL RESULT Overlap Detected! Output: true OK Rectangles share a positive area intersection. !(L||R||B||T) Key Insight: Instead of checking if rectangles overlap (complex), check if they DON'T overlap (simpler). Two rectangles don't overlap if one is completely to the left, right, above, or below the other. Overlap = NOT(rec1.right <= rec2.left OR rec1.left >= rec2.right OR rec1.top <= rec2.bottom OR rec1.bottom >= rec2.top) TutorialsPoint - Rectangle Overlap | Optimized - Non-Overlap Conditions
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
25.0K Views
Medium Frequency
~10 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen