Arranging Coins

Find how many full rows a staircase of n coins can have, when row i holds i coins.

Given n coins, build a staircase out of them: the first row gets 1 coin, the second row 2 coins, and row i gets i coins. The last row may be left unfinished. Return the number of complete rows.

Example 1
Input: n = 5
Output: 2
Explanation: rows 1 and 2 use 3 coins, and the 2 coins left cannot fill row 3.
Example 2
Input: n = 8
Output: 3
Explanation: rows 1, 2 and 3 use 6 coins, and the 2 coins left cannot fill row 4.
Solution

The Idea

Picture laying coins on a table, row under row, each row one coin longer than the row above. Take the 8 coins of Example 2. Row 1 takes 1 coin, row 2 takes 2 and row 3 takes 3, which uses 6 coins. The 2 coins left go into row 4, but row 4 needs 4, so it stays unfinished. The answer is 3.

The obvious way to solve it is to do just that: lay the rows one by one and subtract their coins until the next row no longer fits. For 8 coins that is quick. For 2,147,483,647 coins, the largest Java int, it takes 65,535 steps, one per row. Can we jump to the right number of rows instead of counting up to it?

Turn the question around. Instead of laying rows, pick any number of rows, call it k, and ask: do k complete rows fit into the coins we have? Look at the picture below.

Left: 8 coins as a staircase, rows 1 to 3 full and row 4 with 2 of its 4 coins. Right: k rows need 1, 3, 6, 10 and 15 coins for k = 1 to 5; with 8 coins, k = 1 to 3 fit and k = 4 and 5 need too many.

On the left are the 8 coins, with two empty spots in row 4. On the right, the table lists the coins needed for k rows. The rows for k = 1, 2 and 3 say "fits", and from k = 4 on they say "too many".

That pattern holds for any number of coins, because every extra row needs more coins than the rows before it. Once some k is too many, every bigger k is too many as well. So the answers run "fits, fits, ..., fits, too many, too many, ...", and the problem asks for the last k that fits, here 3.

Finding the point where a yes-or-no answer flips is what binary search is good at. It checks the middle of a range of candidates and throws away the half that cannot hold the answer, so every check halves the range. Here the candidates are not the items of an array but the possible numbers of rows.

Solution Approach

Turning that idea into code means settling four things: how to count the coins that k rows need, which range of row counts to search, how to pick the middle so the search always ends, and which number type holds the counts.

Coins needed for k rows

How many coins do k complete rows need? They need 1 + 2 + ... + k, and adding that up one row at a time would bring back the slow way. There is a shortcut. Write the sum twice, once forward and once backward, for example 1 + 2 + 3 + 4 and 4 + 3 + 2 + 1.

Each column, such as 1 + 4 or 2 + 3, adds up to 5, which is k + 1. There are k columns, so twice the sum is k(k + 1), and the sum itself is k(k + 1) / 2. For 4 rows that is 4 × 5 / 2 = 10 coins, the row labelled k = 4 in the picture.

The range of row counts

Where can the answer be? At least 0 rows, which is what 0 coins give. At most n rows, because every row needs at least one coin. So the search keeps a range from lo = 0 to hi = n and narrows it until one value is left.

The search runs as a loop, and each pass of the loop takes a row count mid in the middle of the range and checks it. If mid rows fit, the answer is mid or bigger, so lo = mid; mid stays in the range because it may be the answer. If they do not fit, the answer is smaller than mid, so hi = mid - 1.

Rounding the middle up

Which middle do we take when the range has two values, say lo = 2 and hi = 3? The usual middle, (lo + hi) / 2, rounds down and gives 2. With 8 coins, 2 rows fit, so lo = mid sets lo to 2 again. The range never shrinks and the loop runs forever.

Rounding up, with mid = lo + (hi - lo + 1) / 2, picks 3 instead, so every pass changes lo or hi. For 8 coins the search goes like this. lo = 0 and hi = 8 give mid = 4, which needs 10 coins, so hi = 3. Then mid = 2 needs 3 coins and fits, so lo = 2. Then mid = 3 needs 6 coins and fits, so lo = 3, which equals hi: the answer is 3.

Counting in long

Can the coin count itself go wrong? The product mid * (mid + 1) grows much faster than the number of coins, but an int stops at 2,147,483,647, the same limit as the largest n. A product past that limit wraps around through the negative numbers and goes on counting from there, which is called overflow. In int arithmetic, 65,536 × 65,537 comes out as 65,536.

For the largest n, the first mid is already 1,073,741,824, and mid * (mid + 1) is about 1.15 × 1018. That does not fit in an int, but it fits in a long, which goes up to about 9.2 × 1018. So lo, hi and mid are all long.

Optional: a formula instead of a search

Is a search needed at all? Solving k(k + 1) / 2 = n for k with the quadratic formula gives the answer directly: (int) ((Math.sqrt(8.0 * n + 1) - 1) / 2). It relies on floating-point square roots, which are rounded. Checked against the row-by-row count for every int value of n, it gave the same answer each time. Binary search uses only whole numbers, so it needs no such check.

Java Solution

The method arrangeCoins works in these steps:

  1. First, set lo = 0 and hi = n, both long: the smallest and largest possible numbers of rows.
  2. Loop while lo is less than hi. In each pass, compute mid = lo + (hi - lo + 1) / 2, the middle of the range rounded up.
  3. Check whether mid rows fit, with mid * (mid + 1) / 2 <= n. If they fit, set lo = mid; if not, set hi = mid - 1.
  4. When the loop ends, lo equals hi, and that value is the answer. Return it as an int.

The main method runs both examples, 6 coins (an exact staircase of 3 rows), 1 coin, 0 coins, and the largest int.

Java
public class ArrangingCoins {

    // Largest k with 1 + 2 + ... + k = k(k + 1) / 2 <= n
    public static int arrangeCoins(int n) {
        long lo = 0;
        long hi = n;
        while (lo < hi) {
            long mid = lo + (hi - lo + 1) / 2;    // round up, so lo = mid always makes progress
            if (mid * (mid + 1) / 2 <= n) {
                lo = mid;                         // mid full rows fit
            } else {
                hi = mid - 1;                     // mid rows need too many coins
            }
        }
        return (int) lo;
    }

    public static void main(String[] args) {
        int[] tests = {5, 8, 6, 1, 0, 2147483647};
        for (int n : tests) {
            System.out.println("n = " + n + " -> " + arrangeCoins(n));
        }
    }
}

Running it prints:

Output
n = 5 -> 2
n = 8 -> 3
n = 6 -> 3
n = 1 -> 1
n = 0 -> 0
n = 2147483647 -> 65535

Look at n = 6 -> 3. Six coins fill rows 1, 2 and 3 with none left over, and the check uses <=, so a row that takes the very last coin still counts as complete. For n = 0, lo and hi both start at 0, so the loop never runs and the method returns 0.

The last line says 2,147,483,647 coins make 65,535 full rows. Those rows use 2,147,450,880 coins, and row 65,536 would need 65,536 more, which is more than the 32,767 coins left. Getting there took 31 passes of the loop, against 65,535 steps for laying the rows one by one.

To see the rounding problem for real, change the mid line to lo + (hi - lo) / 2, which rounds down. With that change, n = 5 still returns 2, but n = 8 and n = 3 get stuck with lo = 2 and hi = 3 and never return.

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

Complexity

The work is one binary search over the row counts 0 to n, with a fixed amount of arithmetic in each pass.

  • Time: O(log n), because each pass halves the range of n + 1 possible row counts. For the largest int that is 31 passes.
  • Space: O(1), because the method keeps only lo, hi and mid, however many coins there are.