← Back to index
HardPython4 min read

Perfect Rectangle

check if rectangles form exact rectangle without gaps or overlaps using corner counting and area validation.

geometryhashing

Problem link

View on LeetCode

Solutions in this repo

  • Python../Python/perfect-rectangle/solution.pyPython solution

check two conditions: total area equals expected area, and corner counts are valid. expected rectangle has 4 corners appearing once, all other corners appear even times.

count occurrences of each corner point. if rectangles form perfect rectangle, interior corners cancel out (appear twice), only boundary corners remain.

validation

  • total area must equal (max_x - min_x) * (max_y - min_y)
  • four corner points must appear exactly once
  • all other points must appear even number of times

complexity

O(n) time where n is number of rectangles. O(n) space for corner counts.