Number of Pairs of Interchangeable Rectangles Problem
Description
LeetCode Problem 2001.
You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [width_i, height_i] denotes the width and height of the i^th rectangle.
Two rectangles i and j (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if width_i/height_i == width_j/height_j (using decimal division, not integer division).
Return the number of pairs of interchangeable rectangles in rectangles.
Example 1:
Input: rectangles = [[4,8],[3,6],[10,20],[15,30]]
Output: 6
Explanation: The following are the interchangeable pairs of rectangles by index (0-indexed):
- Rectangle 0 with rectangle 1: 4/8 == 3/6.
- Rectangle 0 with rectangle 2: 4/8 == 10/20.
- Rectangle 0 with rectangle 3: 4/8 == 15/30.
- Rectangle 1 with rectangle 2: 3/6 == 10/20.
- Rectangle 1 with rectangle 3: 3/6 == 15/30.
- Rectangle 2 with rectangle 3: 10/20 == 15/30.
Example 2:
Input: rectangles = [[4,5],[7,8]]
Output: 0
Explanation: There are no interchangeable pairs of rectangles.
Constraints:
n == rectangles.length1 <= n <= 10^5rectangles[i].length == 21 <= width_i, height_i <= 10^5
Solution
Approach: Reduced Ratio and Hash Map
Two rectangles are interchangeable when w1 / h1 == w2 / h2. Floating-point division is unsafe for comparing ratios, so represent each ratio exactly: divide both sides by their greatest common divisor to get the pair (w / g, h / g).
Scan the rectangles with a hash map from the reduced pair to the number of rectangles seen with it. When a rectangle arrives, every earlier rectangle with the same reduced pair forms one new pair, so add that count to the answer, then increase the count.
The answer can reach about 5 * 109, so use a 64-bit integer.
Complexity: O(n log M) time for the gcds and O(n) space, where M is the largest side length.
from collections import Counter
from math import gcd
class Solution:
def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:
ans = 0
cnt = Counter()
for w, h in rectangles:
g = gcd(w, h)
w, h = w // g, h // g
ans += cnt[(w, h)]
cnt[(w, h)] += 1
return ans