Number of Pairs of Interchangeable Rectangles - Problem

You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle.

Two rectangles i and j (where i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj (using decimal division, not integer division).

Return the number of pairs of interchangeable rectangles in rectangles.

Input & Output

Example 1 — Basic Case
$ Input: rectangles = [[4,6],[8,10],[4,8],[2,4]]
Output: 1
💡 Note: Rectangles [4,8] and [2,4] have the same ratio 1:2 (4/8 = 2/4 = 0.5), forming 1 interchangeable pair
Example 2 — Multiple Groups
$ Input: rectangles = [[4,8],[3,6],[10,20],[12,16]]
Output: 3
💡 Note: Rectangles [4,8], [3,6], and [10,20] all have ratio 1/2, while [12,16] has ratio 3/4. The 3 rectangles with ratio 1/2 form C(3,2) = 3 pairs
Example 3 — No Matches
$ Input: rectangles = [[1,2],[2,3],[3,4]]
Output: 0
💡 Note: All rectangles have different ratios: 1/2, 2/3, 3/4. No pairs are interchangeable

Constraints

  • n == rectangles.length
  • 1 ≤ n ≤ 105
  • rectangles[i].length == 2
  • 1 ≤ widthi, heighti ≤ 105

Visualization

Tap to expand
Interchangeable Rectangles INPUT 4 Rectangles: [4,6] i=0 [8,10] i=1 [4,8] i=2 [2,4] i=3 Width/Height Ratios: 4/6 = 0.667 8/10 = 0.800 4/8 = 0.500 2/4 = 0.500 Input Array: [[4,6],[8,10],[4,8],[2,4]] n = 4 rectangles ALGORITHM STEPS 1 Create Hash Map Store ratio as key (GCD form) 2 Calculate Ratios Reduce to lowest terms HashMap Key (ratio) Count 2:3 (4/6) 1 4:5 (8/10) 1 1:2 (4/8,2/4) 2 3 Count Pairs For count n: pairs = n*(n-1)/2 4 Sum All Pairs Ratio 1:2 has 2 rects Pairs = 2*(2-1)/2 = 1 FINAL RESULT Matching Pair Found: [4,8] i=2 = [2,4] i=3 Both have ratio 1:2 4/8 = 2/4 = 0.5 Other ratios (no pairs): 2:3 -- 1 rect -- 0 pairs 4:5 -- 1 rect -- 0 pairs Output: 1 Key Insight: Use a HashMap to group rectangles by their width/height ratio. To avoid floating-point precision issues, store ratios as reduced fractions (using GCD). For each ratio with count n, the number of pairs is n*(n-1)/2. Time Complexity: O(n) | Space Complexity: O(n) TutorialsPoint - Number of Pairs of Interchangeable Rectangles | Hash Approach
Asked in
Google 15 Amazon 12 Facebook 8
28.0K Views
Medium Frequency
~25 min Avg. Time
890 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