Arranging Coins - Problem

You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the i-th 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.

Input & Output

Example 1 — Basic Case
$ Input: n = 5
Output: 2
💡 Note: Row 1: 1 coin (4 left), Row 2: 2 coins (2 left), Row 3 needs 3 coins but only 2 left. So 2 complete rows.
Example 2 — Perfect Triangle
$ Input: n = 3
Output: 2
💡 Note: Row 1: 1 coin (2 left), Row 2: 2 coins (0 left). Exactly 2 complete rows with no coins remaining.
Example 3 — Large Number
$ Input: n = 8
Output: 3
💡 Note: Row 1: 1 coin, Row 2: 2 coins, Row 3: 3 coins (total 6), Row 4 needs 4 but only 2 left. So 3 complete rows.

Constraints

  • 1 ≤ n ≤ 231 - 1

Visualization

Tap to expand
Arranging Coins - Optimal Solution INPUT n = 5 coins to arrange Row 1: $ OK Row 2: $ $ OK Row 3: $ $ ? incomplete n = 5 (total coins) Row i needs i coins Total for k rows: k*(k+1)/2 1+2+3 = 6 > 5 ALGORITHM STEPS 1 Binary Search Setup left=0, right=n left=0, right=5 2 Calculate Mid mid = (left + right) / 2 mid = (0+5)/2 = 2 3 Check Coins Needed coins = mid*(mid+1)/2 2*(2+1)/2 = 3 <= 5 4 Adjust Search Range If coins <= n: left = mid+1 Else: right = mid-1 Search Progress: [0,5] mid=2: 3<=5 left=3 [3,5] mid=4: 10>5 right=3 [3,3] mid=3: 6>5 right=2 left>right: return 2 FINAL RESULT Complete rows built: Row 1: $ 1/1 Row 2: $ $ 2/2 Row 3: $ $ 2/3 Used: 1 + 2 = 3 coins Remaining: 2 coins Output: 2 2 complete rows Time: O(log n) Key Insight: Binary search finds the largest k where k*(k+1)/2 <= n. This is the mathematical formula for triangular numbers (sum 1+2+...+k). Instead of counting row by row, we efficiently search for the answer in O(log n) time using this property. TutorialsPoint - Arranging Coins | Optimal Solution (Binary Search)
Asked in
Google 15 Amazon 12 Microsoft 8
111.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen