Number of Pairs of Interchangeable Rectangles
You are given nrectanglesrectangles[i] = [widthi, heighti]ith
Two rectangles iji < jwidthi/heighti == widthj/heightj
Return the number of pairs of interchangeable rectangles in rectangles.
Example 1
Output: 6
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.
Example 2
Output: 0
Explanation: There are no interchangeable pairs of rectangles.
Constraints:
1 <= nums.length <= 2 * 104-1000 <= nums[i] <= 1000-107 <= k <= 107
Solution 1 - Store ratio counts and find unique pairs of answers
In this approach, we are going to compute width-to-height ratio and store them into a HashMapratioHashMap
Implementation steps:
-
Create a
to store width-to-height counts, and call itHashMap .ratioCount -
Iterate through each rectangle from input
.rectangles -
Next, calculate the width-to-height ratio for each rectangle.
Java
double ratio = (double) rectangle[0] / rectangle[1]; -
In next step, store this into
ratioCount , if theHashMap is already exist, increment value byratio , otherwise add1 .1 -
Now, go through each ratio count stored in
ratioCount , calculate the number of pairs that can be formed using the count of rectangles with that ratio.HashMap-
The number of pairs for a count
of rectangles with the same ratio isn
For example, if the input is , all the rectangles will have same ratiorectangles = [[4,8],[3,6],[10,20],[15,30]] and the count of rectangles is0.5 , to get the unique pairs of rectangles we can use4 .4 *3 / 2
Unique pairs are ,[4,8],[3,6] ,[4,8],[10,20] ,[4,8],[15,30] ,[3,6],[10,20] and[3,6],[15,30] .[10,20],[15,30] -
The number of pairs for a count
Note:
A generic formula to calculate kn
import java.util.HashMap;
public class InterChangeableRectanglePairs {
static long interchangeableRectangles(int[][] rectangles) {
HashMap<Double, Long> ratioCount = new HashMap<>();
// calculate and store the ratio counts
for(int[] rectangle: rectangles) {
double ratio = (double)rectangle[0] / rectangle[1];
ratioCount.merge(ratio, 1l, Long::sum);
}
//calculate pairs for each unique ratio
//Generic formula for an array of n numbers with k distinct groupings
// n! / (n-k)! * k!
int result = 0;
for(Long uniquePairCount: ratioCount.values()) {
result += (uniquePairCount * (uniquePairCount -1) ) /2;
}
return result;
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n) time where nrectangles
Space complexity: O(n), since we are storing width-to-height ratios into a HashMap
Above implementations source code can be found at