← Questions

Intersection of two rectangles

0
FigmaCodingLast asked Aug 2024

A coding interview question asked in Figma's technical phone screen, last asked Aug 2024. It tests geometry and intervals.

Two axis-aligned rectangles are each given as [left, bottom, right, top]. Return the rectangle where they overlap, in the same format, or an empty list if they do not overlap with positive area. Rectangles that only touch along an edge or at a corner do not overlap.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • intersect(first: list[int], second: list[int]) -> list[int]

Example

intersect([0, 0, 4, 4], [2, 1, 6, 3])     ->  [2, 1, 4, 3]
intersect([-3, -2, 5, 7], [0, 0, 2, 2])   ->  [0, 0, 2, 2]    # second is inside first
intersect([0, 0, 2, 2], [2, 0, 5, 3])     ->  []              # touch along x = 2 only

Constraints

  • left < right and bottom < top; coordinates are between -10^9 and 10^9.

Clarifying questions

  • Does touching at an edge count as an intersection? (No.)
  • Are coordinates integers or floats?
  • Should the function return the area instead of the rectangle?

What a strong answer covers

  • Intersecting the x-ranges and the y-ranges separately: left = max(l1, l2), right = min(r1, r2), and the same for bottom and top.
  • An overlap exists only when left < right and bottom < top (strict, to exclude touching).
  • O(1) time.
  • Tests: containment, touching edges, touching corners, no overlap, identical rectangles.

Follow-ups

  • Return the area of the union of the two rectangles.
  • Given n rectangles, find whether any two overlap (sweep line, O(n log n)).
  • Compute the total area covered by n rectangles.
  • Rectangles can be rotated.

Where it's asked

  • Figma · Technical phone screen · Last asked Aug 202460 min · Pair programming in your own language against tests the interviewer provides

What it tests

geometry · intervals

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding