You have n coins and lay them out as a staircase: the first row gets 1 coin, the second row 2 coins, the third row 3 coins, and so on. Each row must be finished before the next one starts, so only the last row can end up short.
Return how many rows are complete.
Example 1
Input: n = 10 Output: 4 Why: 1 + 2 + 3 + 4 uses all 10 coins
2 more examples and the constraints
Example 2
Input: n = 7 Output: 3 Why: rows 1 to 3 use 6 coins; 1 coin cannot fill row 4
Example 3
Input: n = 1 Output: 1 Why: one coin fills the first row
Constraints
- 1 ≤ n ≤ 2,147,483,647 (2^31 − 1)
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Build the rows one by oneO(√n)
- Binary search on the row countO(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 2^31 − 1 | Verdict |
|---|---|---|---|
| Build the rows one by one | O(√n) | Passes; 65,535 rows at most | |
| Binary search on the row count | O(log n) | Best; about 31 checks |
n = number of coins.
Edge cases to test
- One coin. It fills row 1, so the answer is 1.
- An exact staircase. n = 10 fills rows 1 to 4 with nothing left: 4, not 3.
- One coin short. n = 9 cannot finish row 4, so the answer is 3.
- The largest n. 2,147,483,647 coins give 65,535 rows; mid·(mid + 1) overflows 32 bits on the way.
Common mistakes
- Computing mid·(mid + 1) in 32-bit integers, which overflows for large n.
- Rounding mid down with
lo = mid, which loops forever on a range of two values. - Returning the row that ran out of coins instead of the last full one.
How to talk through it
- 1Clarify. Only complete rows count? Can n be as large as 2^31 − 1?
- 2Give the simple loop. Lay rows until the next one does not fit; it runs about √(2n) times.
- 3Find the monotone test. k rows need k(k + 1)/2 coins, which grows with k, so binary search the largest k that fits.
- 4Code it carefully. Round mid up and use 64-bit math for the product.
- 5Test out loud. Run n = 1, an exact staircase like 10, and the largest n.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?