Number of Pairs of Interchangeable Rectangles
Count the pairs of rectangles that have the same shape, by reducing each width-to-height ratio to lowest terms.
You are given an array rectangles[width, height]
Example 1
Output: 6
Explanation: every rectangle has width / height = 0.5, so each of the 6 possible pairs is interchangeable.
Example 2
Output: 0
Explanation: 4 / 5 = 0.8 and 7 / 8 = 0.875 are different.
The Idea
When you enlarge a photo without stretching it, the width and the height grow by the same factor, so the picture keeps its shape. A 3 by 6 rectangle and a 15 by 30 rectangle have the same shape in that sense: the second is the first, five times bigger. Width divided by height tells the shapes apart, and is called the ratio. Two rectangles are interchangeable exactly when they have the same ratio.
Look at Example 1. All four rectangles are twice as tall as they are wide, so all four have the ratio 1/2. With four rectangles there are 6 ways to pick two of them, and every one of those pairs counts, which gives 6. Example 2 has two rectangles of slightly different shapes, so it gives 0.
Checking every pair works for four rectangles, but 100,000 rectangles make almost 5 billion pairs. Is there a way to count pairs without looking at them one by one?
There is, if we go through the rectangles in order, keep a running total of pairs, and remember how many rectangles of each ratio we have met so far. A new rectangle makes one pair with each earlier rectangle of its ratio, and with no other rectangle. So when it arrives, we add the number of earlier rectangles with its ratio to the running total. Look at the picture below.
The rectangles are drawn to scale, from left to right in the order of the array. In the row "divide by gcd", both sides of each rectangle are divided by the largest number that divides both, called their greatest common divisor, or gcd: 4 for [4, 8][4, 8][15, 30]
So the whole problem comes down to one pass over the array and a count per ratio, with each ratio written as a reduced fraction so that equal shapes always match.
Solution Approach
Turning that idea into code means settling three things: how to write a ratio so that equal ratios match exactly, where to keep the count for each ratio, and how big the total can get.
Writing a ratio exactly
Why not simply divide, and use width / heightint
Dividing as a doubledoubledouble
A fraction in lowest terms has no such problem. 4/8, 3/6, 10/20 and 15/30 are all the same fraction, 1/2, once each is reduced. To reduce a fraction, divide both the width and the height by their gcd, as in the picture. The gcd of 10 and 20 is 10, and 10 / 10 = 1 and 20 / 10 = 2. Two rectangles have the same ratio exactly when their reduced fractions are equal, so the reduced width and height can be compared as plain whole numbers.
How is the gcd found? An old method called Euclid's algorithm uses one fact: the gcd of a and b is the same as the gcd of b and the remainder of a divided by b. Repeat that until the remainder is 0. For 10 and 20, the remainder of 10 / 20 is 10, so the method moves on to 20 and 10. The remainder of 20 / 10 is 0, so the gcd is 10.
Counting each ratio
Where is the count for each ratio kept? A HashMaplong
Why a longintlong
How big the total gets
Can the answer itself be too large for an intintlong
Java Solution
The method interchangeableRectangles
- First, create the map
, from a reduced ratio to the number of rectangles with that ratio met so far, and set the totalseen to 0.pairs - Go through the rectangles with one loop, taking each as
. Find the gcd of its width and height withr and store it ingcd(r[0], r[1]) .g - Divide the width and the height by
, and pack the two reduced values into theg numberlong : the width times 1,000,000, plus the height.key - Look up how many earlier rectangles had this
, askey , and addbefore tobefore . Then storepairs in the map, to count the current rectangle.before + 1 - When the loop is done, return
.pairs
The helper gcdba % babab
The main
import java.util.HashMap;
import java.util.Map;
public class NumberOfPairsOfInterchangeableRectangles {
public static long interchangeableRectangles(int[][] rectangles) {
Map<Long, Integer> seen = new HashMap<>(); // reduced ratio -> rectangles so far
long pairs = 0;
for (int[] r : rectangles) {
int g = gcd(r[0], r[1]);
long key = (long) (r[0] / g) * 1000000L + r[1] / g; // reduced width and height
int before = seen.getOrDefault(key, 0);
pairs += before; // one pair with each earlier rectangle
seen.put(key, before + 1);
}
return pairs;
}
private static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static void main(String[] args) {
System.out.println(interchangeableRectangles(
new int[][] {{4, 8}, {3, 6}, {10, 20}, {15, 30}}));
System.out.println(interchangeableRectangles(new int[][] {{4, 5}, {7, 8}}));
System.out.println(interchangeableRectangles(
new int[][] {{2, 3}, {4, 6}, {3, 2}, {6, 4}, {9, 6}}));
System.out.println(interchangeableRectangles(new int[][] {{7, 7}}));
int[][] squares = new int[100000][];
for (int i = 0; i < squares.length; i++) {
squares[i] = new int[] {i + 1, i + 1};
}
System.out.println(interchangeableRectangles(squares));
}
}
Running it prints:
6
0
4
0
4999950000
The first two lines, 60[2, 3][4, 6][3, 2][6, 4][9, 6]
The fourth line is 0, since a single rectangle has nothing to pair with. The last line comes from 100,000 squares, from 1 by 1 up to 100,000 by 100,000. They all reduce to 1/1, and the total 4,999,950,000 only prints correctly because pairslong
Keying the map on r[0] / r[1]int
The original implementation,
Complexity
The work is one gcd and one map update for each rectangle.
- Time: O(n log V), where n is the number of rectangles and V is the largest side. Euclid's algorithm takes O(log V) steps, because the numbers shrink at least by half every two steps. The map lookup and update take O(1) on average.
- Space: O(n). The map
holds one entry per different ratio, so at most n entries. The calls ofseen go only O(log V) deep.gcd
Keeping a map of what the loop has met so far, and checking each new item against it, is also how