LeetCode solutions

2129. Number of Pairs of Interchangeable Rectangles

My accepted Python solution to LeetCode problem 2129, Number of Pairs of Interchangeable Rectangles, running in 136ms.

  • Difficulty: Medium
  • Python
  • Runtime 136ms
  • Memory 66.7MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 136ms, memory 66.7MB, accepted 2025-12-29.

python
class Solution:
    def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:
        from math import gcd
        from collections import Counter
        
        ratios = Counter()
        for w, h in rectangles:
            g = gcd(w, h)
            ratios[(w // g, h // g)] += 1
        
        count = 0
        for freq in ratios.values():
            count += freq * (freq - 1) // 2
        
        return count

Source