#2001

Number of Pairs of Interchangeable Rectangles

Medium
ArrayHash TableMathCountingNumber TheoryHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of checking every pair, we can use a hashmap to count how many rectangles share the same width-to-height ratio. This way, we can calculate the number of interchangeable pairs in linear time.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a hashmap to store the frequency of each ratio in reduced form.
  2. 2Step 2: For each rectangle, compute the width and height ratio in reduced form using the greatest common divisor (GCD).
  3. 3Step 3: Increment the count in the hashmap for this ratio.
  4. 4Step 4: For each unique ratio in the hashmap, calculate the number of interchangeable pairs using the formula: count * (count - 1) / 2.
solution.py14 lines
1# Full working Python code
2from collections import defaultdict
3from math import gcd
4class Solution:
5    def interchangeableRectangles(self, rectangles):
6        ratio_count = defaultdict(int)
7        for width, height in rectangles:
8            g = gcd(width, height)
9            ratio = (width // g, height // g)
10            ratio_count[ratio] += 1
11        count = 0
12        for freq in ratio_count.values():
13            count += freq * (freq - 1) // 2
14        return count

Complexity note: This complexity is due to iterating through the rectangles once and storing the ratios in a hashmap, which is efficient for counting.

  • 1Understanding how to reduce ratios using GCD is crucial for this problem.
  • 2Using a hashmap allows for efficient counting of occurrences, avoiding the need for nested loops.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.