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, where each entry is a rectangle written as [width, height]. Two rectangles are interchangeable when the width divided by the height gives the same number for both, using exact division: 4 / 8 and 3 / 6 are both 0.5. Return how many pairs of rectangles, taken from two different positions in the array, are interchangeable. There are up to 100,000 rectangles, and each side is a whole number from 1 to 100,000.

Example 1
Input: rectangles = [[4, 8], [3, 6], [10, 20], [15, 30]]
Output: 6
Explanation: every rectangle has width / height = 0.5, so each of the 6 possible pairs is interchangeable.
Example 2
Input: rectangles = [[4, 5], [7, 8]]
Output: 0
Explanation: 4 / 5 = 0.8 and 7 / 8 = 0.875 are different.
Solution

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 [4, 8], [3, 6], [10, 20] and [15, 30] have the same shape. Dividing each side by the gcd gives the reduced ratio 1/2 every time. Each rectangle pairs with the earlier ones of ratio 1/2: 0, 1, 2 and 3 of them, so the pairs so far grow 0, 1, 3, 6.

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], which leaves 1 and 2. The row "reduced ratio" shows the result, 1/2, under every rectangle. The row "earlier with 1/2" counts the rectangles of that ratio to the left: 0 for [4, 8], then 1, 2 and 3. The last rectangle, [15, 30], is joined by dashed lines to the three before it, its three pairs. Adding up the row gives "pairs so far": 0, 1, 3 and finally 6, the answer.

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 / height as the ratio? In Java, dividing two int values drops the fraction part, so 4 / 5 and 7 / 8 both give 0, and the two rectangles of Example 2 would look the same.

Dividing as a double, a number with a fraction part, fixes Example 2: 0.8 and 0.875 differ. But a double keeps only about 16 digits, so two different ratios that are very close can round to the same value. With sides near a billion, 999,999,999 / 1,000,000,000 and 999,999,998 / 999,999,999 are different ratios, yet both come out as the double 0.999999999.

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 HashMap from ratio to count looks up and updates a count in a single step on average, however many ratios it holds. Its key has to be one value, so the reduced width and height are packed into one long: the width times 1,000,000, plus the height. A reduced height is at most 100,000, below 1,000,000, so the two parts never mix. The ratio 1/2 becomes 1,000,002.

Why a long? The reduced width can be 100,000 too, and 100,000 times 1,000,000 is 100 billion. A Java int only holds values up to 2,147,483,647, about 2.1 billion, while a long holds far bigger ones.

How big the total gets

Can the answer itself be too large for an int? If all 100,000 rectangles have the same ratio, every pair counts, and there are 100,000 × 99,999 / 2 = 4,999,950,000 pairs. That is more than 2,147,483,647. An int that goes past its largest value continues from the most negative values, which is called overflow, and this total would come out as 704,982,704. So the total is kept in a long as well.

Java Solution

The method interchangeableRectangles works in these steps:

  1. First, create the map seen, from a reduced ratio to the number of rectangles with that ratio met so far, and set the total pairs to 0.
  2. Go through the rectangles with one loop, taking each as r. Find the gcd of its width and height with gcd(r[0], r[1]) and store it in g.
  3. Divide the width and the height by g, and pack the two reduced values into the long number key: the width times 1,000,000, plus the height.
  4. Look up how many earlier rectangles had this key, as before, and add before to pairs. Then store before + 1 in the map, to count the current rectangle.
  5. When the loop is done, return pairs.

The helper gcd is Euclid's algorithm: it calls itself with b and a % b, the remainder of a divided by b, and returns a once b is 0.

The main method runs both examples, a mix of 2 by 3 and 3 by 2 rectangles, a single square, and 100,000 squares of different sizes.

Java
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:

Output
6
0
4
0
4999950000

The first two lines, 6 and 0, answer the two examples. Look at the third line, 4. The rectangles [2, 3] and [4, 6] both reduce to 2/3, which gives 1 pair. [3, 2], [6, 4] and [9, 6] all reduce to 3/2, which gives 3 more. A 2 by 3 rectangle and a 3 by 2 rectangle are not counted together, because the width always comes first.

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 pairs is a long.

Keying the map on r[0] / r[1] as an int instead fails on Example 2. Both rectangles get the key 0, and that version returns 1 instead of 0.

The original implementation, InterChangeableRectanglePairs.java, is on GitHub.

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 seen holds one entry per different ratio, so at most n entries. The calls of gcd go only O(log V) deep.

Keeping a map of what the loop has met so far, and checking each new item against it, is also how Two Sum avoids comparing every pair.