Arranging Coins

You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete. Given the integer n, return the number of complete rows of the staircase you will build.

30:00

Arranging Coins
easy
Free written solution
Topics
Companies

You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete. Given the integer n, return the number of complete rows of the staircase you will build.

Example 1:
Input: {"n":5}
Output: 2
Constraints:
  • 1≤n≤231−11 \leq n \leq 2^{31} - 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":5}

A staircase of k full rows uses 1 + 2 + ... + k = k(k+1)/2 coins, which grows with k. Binary search the largest k whose staircase fits in n = 5 coins, starting from [0, 5].

staircase

Row i holds i coins. Rows: 1, 2, 3, ... Total for k rows = k(k+1)/2.

search range for k

lo = 0

hi = 5

probes

none yet

Variables
VariableValue
n5
lo0
hi5
DepthFunction Call
Stack empty
0/7