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
Key insight: Two rectangles are interchangeable when
Goal: Return the total number of interchangeable rectangle pairs.
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
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
โ Linear Growth
Space Complexity
O(n)
Hash map can store up to n different ratios in worst case
โก Linearithmic Space
Constraints
- n == rectangles.length
- 1 โค n โค 105
- rectangles[i].length == 2
- 1 โค widthi, heighti โค 105
- All dimensions are positive integers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code