⚡Flashcard Drill➔
NeetCode #117LC-2001MediumArrays & Hashing
← Back to All Problems

#117 · #2001 · Number of Pairs of Interchangeable Rectangles(可互换矩形的组数)

📌 Problem Statement & Constraints

You are given n rectangles, each [width_i, height_i]. Two rectangles are interchangeable if their width-to-height ratios are equal. Count the number of pairs (i, j) with i < j that are interchangeable. Constraints: 1 <= n <= 10^5, 1 <= width_i, height_i <= 10^5.

💡 Core Algorithmic Approaches

  1. Two rectangles have the same ratio exactly when the reduced fraction (width / g, height / g) is identical, where g = gcd(width, height).
  2. Represent the reduced fraction as a tuple key and count how many rectangles fall into each group.
  3. A group of size c contributes C(c, 2) = c * (c - 1) / 2 pairs.
  4. Using the reduced integer pair avoids floating-point comparison errors entirely.

💻 Benchmark Python3 Implementation

class Solution:
    def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:
        from collections import defaultdict
        from math import gcd
        cnt = defaultdict(int)
        for w, h in rectangles:
            g = gcd(w, h)
            cnt[(w // g, h // g)] += 1     # reduced fraction as the key
        return sum(c * (c - 1) // 2 for c in cnt.values())

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n log V): each gcd is O(log V), and the summation is over the groups.
💾 Space Complexity
O(n) for the groups.

⚠️ Interview Pitfalls & Follow-ups

  • Comparing floats: w / h introduces rounding, and two mathematically equal ratios can differ in the last bit. Use reduced integer pairs.
  • Forgetting to reduce the fraction: (2, 4) and (1, 2) must map to the same key.
  • Counting ordered pairs: the requirement is i < j, so use the combination formula.
  • Using w * h or the sum as the key: those are not invariants of the ratio.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

可互换矩形的组数

用一个下标从 0 开始的二维整数数组 rectangles 来表示 n 个矩形,其中 rectangles[i] = [widthi, heighti] 表示第 i 个矩形的宽度和高度。如果两个矩形 i 和 j(i &lt; j)的宽高比相同,则认为这两个矩形是 可互换 的。返回可互换矩形对的数目。约束:n == rectangles.length;1 ≤ n ≤ 10^5;1 ≤ widthi, heighti ≤ 10^5。

核心要点

  • 宽高比归一化(标准解) :两个矩形宽高比相同,等价于 w1/h1 == w2/h2 ,即 w1 × h2 == w2 × h1 。
  • 用最简分数作为键 :为避免浮点误差与乘法溢出,把 (w, h) 除以最大公约数化为最简分数 (w/g, h/g) ,作为哈希键。
  • 组合计数 :设某个比值的矩形有 c 个,则它贡献 C(c, 2) = c(c−1)/2 对。也可以边遍历边累加「与之前同比值的矩形数」。
  • 为什么不能用浮点数 : w/h 的双精度表示可能对不同的分数产生相同的值(或对相同的分数产生微小差异),导致误判。最简分数是精确且高效的方案。

常见陷阱

  • 直接用浮点数作键 : w / h 会有精度问题,不同比值可能碰撞或相同比值不相等。必须用最简分数。
  • 用 w * h 或 w / h 的未约分形式作键 : (2, 4) 与 (1, 2) 表示同一比值,不约分会分成两组。必须除以 gcd。
  • 返回 cnt 的某个统计值而非配对总数 :题目要求的是 对 的数目,即所有 C(c, 2) 之和,不是「不同比值的种类数」。
  • 最后统一计算 c(c-1)/2 与边遍历边累加 :两种写法等价;边遍历边累加可以省去最后一次遍历。

参考实现

from collections import defaultdict
from math import gcd

class Solution:
    def interchangeableRectangles(self, rectangles: list[list[int]]) -> int:
        cnt = defaultdict(int)
        ans = 0
        for w, h in rectangles:
            g = gcd(w, h)
            key = (w // g, h // g)      # 最简分数,精确且无浮点误差
            ans += cnt[key]             # 与之前每个同比值的矩形都能配对
            cnt[key] += 1
        return ans