Leetcode 2001: Number of Pairs of Interchangeable Rectangles

grid47
grid47
Exploring patterns and algorithms
Apr 20, 2024 5 min read

You are given a list of rectangles, each represented by its width and height. Two rectangles are interchangeable if their width-to-height ratios are the same. Your task is to return the number of interchangeable rectangle pairs in the list.
Problem
Approach
Steps
Complexity
Input: The input consists of a list of rectangles, where each rectangle is represented as a pair of integers: [width, height]. The number of rectangles is between 1 and 10^5, and each width and height is between 1 and 10^5.
Example: rectangles = [[6,12], [3,6], [5,10], [15,30]]
Constraints:
• 1 <= n <= 10^5
• 1 <= width_i, height_i <= 10^5
• rectangles[i].length == 2
Output: Return the total number of pairs of interchangeable rectangles.
Example: 6
Constraints:
Goal: The goal is to calculate the number of interchangeable pairs of rectangles, which can be done by checking for rectangles with the same width-to-height ratio.
Steps:
• 1. Compute the width-to-height ratio for each rectangle.
• 2. Use a hash map to store the frequency of each unique ratio.
• 3. For each unique ratio, calculate the number of interchangeable pairs using the frequency of that ratio.
• 4. Return the total count of pairs.
Goal: The input list contains between 1 and 10^5 rectangles. Each rectangle has a width and height between 1 and 10^5.
Steps:
• 1 <= n <= 10^5
• 1 <= width_i, height_i <= 10^5
Assumptions:
• The input list contains valid rectangles with width and height values between 1 and 10^5.
Input: rectangles = [[6,12], [3,6], [5,10], [15,30]]
Explanation: The width-to-height ratios for these rectangles are 6/12, 3/6, 5/10, and 15/30, which are all the same. Therefore, all 6 pairs of rectangles are interchangeable.

Input: rectangles = [[6,7], [7,8]]
Explanation: The width-to-height ratios for these rectangles are different, so there are no interchangeable pairs.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus