LeetCode 2001, Medium. Topics: Array, Hash Table, Math, Counting, Number Theory. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:
Problem
You are given n rectangles represented as 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 (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.
Examples
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.
Explanation: There are no interchangeable pairs of rectangles.
Constraints
n == rectangles.length
1 <= n <= 10^5
rectangles[i].length == 2
1 <= widthi, heighti <= 10^5
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026