Arranging Coins solution explained
Arranging Coins asks for the largest k with k(k + 1) / 2 at most n, because a staircase of k full rows uses exactly that many coins. Binary search on k finds it in O(log n) time, and solving the quadratic gives a closed form, floor((√(8n + 1) - 1) / 2), in O(1) when computed with an exact integer square root.
By Evin JohnPublished 7 min read
The problem in plain words
You have n identical coins and lay them out as a staircase: one coin in the first row, two in the second, three in the third, and so on. The last row may end up short. Return the number of rows that are full. The usual version guarantees n is at least 1 and fits in a 32-bit signed integer; ask whether 0 is possible, since the answer for it is simply 0.
| Coins (n) | Full rows | How the coins split |
|---|---|---|
| 1 | 1 | Row 1 takes the only coin |
| 6 | 3 | 1 + 2 + 3 = 6, nothing left |
| 9 | 3 | 6 coins fill three rows; the 3 left over cannot fill row 4 |
| 10 | 4 | 1 + 2 + 3 + 4 = 10 exactly |
| 20 | 5 | 15 coins fill five rows; 5 left over, row 6 needs 6 |
What makes it interview material
Underneath the story is a classic move: recognize a sum you know in closed form, then search or solve for the largest input that keeps it within a budget. It rewards candidates who write the formula 1 + 2 + ... + k = k(k + 1) / 2 on the board before coding. It also hides a subtle binary search detail, because you are looking for the last value that passes a test rather than the first, and the midpoint has to be rounded up to avoid an endless loop.
Slow approach: build the staircase
Simulate it. Keep a row counter and the coins remaining. While there are enough coins for the next row, place it and subtract. When the next row cannot be filled, the counter is the answer. Because k full rows use about k²/2 coins, the loop runs roughly √(2n) times, about 65,000 iterations for the largest 32-bit n. That is fast in practice but still grows with n.
def complete_rows_slow(n):
rows = 0
while n >= rows + 1:
rows += 1
n -= rows
return rowsMain approach: binary search on the row count
Ask a yes or no question about any candidate k: do k full rows fit, meaning k(k + 1) / 2 ≤ n? The answer is yes for small k and no for large k, with a single switch point. You want the last yes. Search over k from 0 to n. If mid fits, the answer is mid or larger, so set lo to mid. If it does not, the answer is smaller, so set hi to mid - 1.
Because the yes branch keeps mid in the range, the midpoint must round up. With lo = 3 and hi = 4, a rounded-down midpoint of 3 that fits leaves lo at 3 forever. Rounding up checks 4 instead, and either moves lo to 4 or hi to 3, so the range always shrinks.
def complete_rows(n):
lo, hi = 0, n
while lo < hi:
mid = (lo + hi + 1) // 2
if mid * (mid + 1) // 2 <= n:
lo = mid
else:
hi = mid - 1
return lofunction completeRows(n) {
let lo = 0;
let hi = n;
while (lo < hi) {
const mid = hi - Math.floor((hi - lo) / 2);
if ((mid * (mid + 1)) / 2 <= n) lo = mid;
else hi = mid - 1;
}
return lo;
}Searching all the way up to n is wasteful but harmless, since the first few probes are huge and get rejected at once. A tighter upper bound such as 2√n is possible, but it adds a line to explain and saves only a few iterations.
Overflow in fixed-width languages
For n near two billion, mid can be near two billion too, and mid × (mid + 1) is around four quintillion, far past a 32-bit int. In Java or C++, compute it in a 64-bit long. In JavaScript the product loses precision when it passes 2^53, but at that size it is vastly larger than n, so the test still fails as it should. Near the real answer, mid is only in the tens of thousands and the arithmetic is exact.
Follow-up: the closed form
Solve k² + k - 2n ≤ 0 for the largest integer k. The positive root of the quadratic is (√(8n + 1) - 1) / 2, so the answer is its floor. With floating point, rounding can bite for very large inputs, so use an exact integer square root where the language has one. Python's math.isqrt returns the exact floor of the square root of an integer, and the integer floor of the root then gives the correct row count.
import math
def complete_rows_formula(n):
return (math.isqrt(8 * n + 1) - 1) // 2function completeRowsFormula(n) {
return Math.floor((Math.sqrt(8 * n + 1) - 1) / 2);
}Why the JavaScript version is safe for this range: 8n + 1 stays below 2^35, Math.sqrt is correctly rounded, and the gap between the square root of a non-square and the next integer is far wider than the rounding error at that size. For inputs beyond 2^50 or so, check the result with one multiplication and adjust by one if needed.
Complexity
| Approach | Time | Extra space | Note |
|---|---|---|---|
| Row-by-row simulation | O(√n) | O(1) | Easiest to get right |
| Binary search on k | O(log n) | O(1) | The expected answer |
| Closed form | O(1) arithmetic | O(1) | Needs care with floating point |
Edge cases to test
- n = 1, the smallest input, which fills exactly one row.
- Exact triangular numbers such as 6, 10 and 15, where no coins are left over.
- One less than a triangular number, such as 14, where the last row falls one coin short.
- n = 2,147,483,647, the 32-bit maximum, to test overflow and float precision.
- n = 0 if the interviewer allows it.
Common mistakes
- Rounding the midpoint down in a last-true search, which hangs when lo and hi are adjacent.
- Returning the number of rows started instead of rows completed, an off-by-one on inputs that are not triangular.
- Multiplying in 32-bit integers and overflowing on large n.
- Trusting a floating square root for 64-bit inputs without a correction step.
- Forgetting the division by two, which roughly halves every answer.
How to explain it out loud
Fictional example
- Candidate
- k full rows cost one plus two up to k coins, which is k times k plus one over two. So I want the largest k where that stays at or below n.
- Candidate
- That test is true then false as k grows, so I binary search for the last true. Since the true branch keeps mid, I round the midpoint up so the loop always makes progress.
- Candidate
- If you want constant time, solving the quadratic gives the floor of root of 8n plus 1, minus 1, over 2. I would use an integer square root to avoid float errors.
Related problems in this set
Guess Number Higher or Lower is the bare form of the search used here. Find Smallest Letter Greater Than Target is the first-true counterpart on a sorted list, a useful contrast to this last-true search. Valid Perfect Square shares the integer square-root idea. The software engineer interview questions page shows where warm-ups like this sit in a full interview loop.
Rehearsing with Natively
While you practice math-flavored problems like this one, Natively can read the statement from a screenshot and suggest an approach, such as searching over k, so you have something to compare with once your own solution runs. The transcript it keeps of a mock session on your computer makes it easy to check whether you said the triangular formula out loud. More on an AI interview assistant for Mac and Windows.
Questions people ask
How do you solve Arranging Coins?
Find the largest k with k(k + 1) / 2 ≤ n. Binary search k from 0 to n, keeping mid when it fits and rounding the midpoint up; that is O(log n).
Is there an O(1) formula for Arranging Coins?
Yes: floor((√(8n + 1) - 1) / 2). Use an exact integer square root, such as Python's math.isqrt, to avoid floating-point errors on large inputs.
Why does my binary search loop forever?
In a search for the last value that passes, setting lo = mid with a rounded-down midpoint stalls when lo and hi are adjacent. Round the midpoint up instead.
Does Arranging Coins overflow in Java?
It can. mid × (mid + 1) exceeds a 32-bit int for large n, so compute it in a long.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
