Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

Complete rows of a coin staircase

Easy · Target 10 minutes · Binary search · Type asked atOptiverAmazon

You build a staircase from n coins: the first row holds 1 coin, the second 2, the k-th row k coins. The last row may be left incomplete. Return the number of complete rows.

Examples

InputOutputWhy
n = 52Rows of 1 and 2 use 3 coins; the third row has only 2 of its 3.
n = 831 + 2 + 3 = 6; the fourth row would need 4 more.
n = 11

Constraints

  • 1 ≤ n ≤ 2³¹ − 1

Hints

Hint 1

k complete rows use 1 + 2 + … + k = k(k + 1)/2 coins.

Hint 2

That total grows with k, so "k(k + 1)/2 ≤ n" is true up to some k and false after it. Find the last true.

Hint 3

k can reach about 65,535 and k(k + 1) about 4.3 × 10⁹, beyond 32 bits. Use 64-bit arithmetic.

Where people lose marks

  • Computing k(k + 1)/2 in 32 bits when k can be close to n.
  • Rounding the midpoint down while setting lo = mid.
  • Returning the number of rows started rather than completed.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.