2001. Number of Pairs of Interchangeable Rectangles
Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 51% Topics: Array, Hash Table, Math, Counting, Number Theory
View full problem on LeetCode Reading material
Reference solution (spoiler · python)
# Time: O(n)
# Space: O(n)
import collections
import fractions
class Solution(object):
def interchangeableRectangles(self, rectangles):
"""
:type rectangles: List[List[int]]
:rtype: int
"""
count = collections.defaultdict(int)
for w, h in rectangles:
g = fractions.gcd(w, h) # Time: O(logx) ~= O(1)
count[(w//g, h//g)] += 1
return sum(c*(c-1)//2 for c in count.itervalues())
Solution from kamyu104/LeetCode-Solutions · MIT