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: Three pairs: [4,8] & [10,20] (ratio 1:2), [3,6] & [12,16] (both simplify to ratio 1:2), and [4,8] & [3,6] & [10,20] & [12,16] all have ratio 1:2, giving us C(4,2) = 6 total 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: Same Aspect Ratio[4,6]ratio: 2/3[8,10]ratio: 4/5[4,8]ratio: 1/2[2,4]ratio: 1/2✓ Same ratio: 1/2Rectangles with identical aspect ratios are interchangeableOutput: 1 interchangeable pair
Understanding the Visualization
1
Input Rectangles
Array of [width, height] pairs representing rectangles
2
Calculate Ratios
Find simplified width:height ratio for each rectangle
3
Count Pairs
Rectangles with same ratio are interchangeable
Key Takeaway
🎯 Key Insight: Rectangles are interchangeable when they have the same simplified width-to-height ratio
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