Number of Pairs of Interchangeable Rectangles - Problem
Imagine you're organizing a collection of rectangular frames and need to find pairs that have the same proportions. Two rectangles are considered interchangeable if they have identical width-to-height ratios - meaning one can be scaled to match the other perfectly!

Given an array rectangles where rectangles[i] = [width_i, height_i], your task is to count how many pairs of rectangles (i, j) where i < j are interchangeable.

Key insight: Two rectangles are interchangeable when width_i / height_i == width_j / height_j. For example, a 4ร—2 rectangle and a 6ร—3 rectangle are interchangeable because both have a ratio of 2:1.

Goal: Return the total number of interchangeable rectangle pairs.

Input & Output

example_1.py โ€” Basic Case
$ Input: rectangles = [[4,6],[6,9],[3,4.5]]
โ€บ Output: 3
๐Ÿ’ก Note: All three rectangles have the same ratio of 2:3 (4/6 = 6/9 = 3/4.5 = 2/3), so we have 3 pairs: (0,1), (0,2), and (1,2)
example_2.py โ€” Mixed Ratios
$ Input: rectangles = [[4,8],[3,3],[2,4],[1,2]]
โ€บ Output: 3
๐Ÿ’ก Note: Rectangles at indices 0,2,3 have ratio 1:2 (4/8 = 2/4 = 1/2), giving us 3 pairs: (0,2), (0,3), (2,3). Rectangle 1 has ratio 1:1 and forms no pairs.
example_3.py โ€” No Pairs
$ Input: rectangles = [[4,5],[7,8]]
โ€บ Output: 0
๐Ÿ’ก Note: The two rectangles have different ratios (4:5 vs 7:8), so no pairs can be formed.

Visualization

Tap to expand
Rectangle Grouping by Aspect Ratio4ร—26ร—38ร—43ร—35ร—5Ratio Group (2:1)Count: 3 rectanglesPairs: 3ร—2รท2 = 3Ratio Group (1:1)Count: 2 rectanglesPairs: 2ร—1รท2 = 1Total Interchangeable Pairs: 3 + 1 = 4Key: Rectangles with the same aspect ratio can be scaled to match each other
Understanding the Visualization
1
Normalize Each Rectangle
Calculate GCD and reduce each rectangle to its simplest ratio form
2
Group by Ratio
Use hash map to count how many rectangles share each normalized ratio
3
Count Combinations
For each group of size k, calculate C(k,2) = kร—(k-1)/2 possible pairs
Key Takeaway
๐ŸŽฏ Key Insight: Instead of comparing all pairs directly (O(nยฒ)), group rectangles by their normalized ratios using GCD, then use the combination formula to count pairs efficiently in O(n) time.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through rectangles, GCD calculation is O(log(min(w,h))) which is negligible

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash map can store up to n different ratios in worst case

n
2n
โšก Linearithmic Space

Constraints

  • n == rectangles.length
  • 1 โ‰ค n โ‰ค 105
  • rectangles[i].length == 2
  • 1 โ‰ค widthi, heighti โ‰ค 105
  • All dimensions are positive integers
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
32.0K Views
Medium Frequency
~15 min Avg. Time
1.3K 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