Arranging Coins - Problem

Imagine you're building a staircase using coins as your building blocks! You have n coins and want to arrange them in a specific pattern where each row contains exactly as many coins as its row number.

The staircase structure works like this:

  • Row 1: 1 coin
  • Row 2: 2 coins
  • Row 3: 3 coins
  • ... and so on

Your task is to find the maximum number of complete rows you can build with your n coins. The last row might be incomplete if you don't have enough coins left.

Example: With 8 coins, you can build 3 complete rows (1+2+3=6 coins used), leaving 2 coins for an incomplete 4th row.

Input & Output

example_1.py — Basic Case
$ Input: n = 5
Output: 2
💡 Note: With 5 coins, we can build 2 complete rows: Row 1 needs 1 coin, Row 2 needs 2 coins (total: 3 coins used). We have 2 coins left, which is not enough for Row 3 (needs 3 coins).
example_2.py — Perfect Triangle
$ Input: n = 6
Output: 3
💡 Note: With 6 coins, we can build exactly 3 complete rows: 1 + 2 + 3 = 6 coins. This forms a perfect triangular number where all coins are used.
example_3.py — Single Coin
$ Input: n = 1
Output: 1
💡 Note: With only 1 coin, we can build 1 complete row (Row 1 needs exactly 1 coin).

Visualization

Tap to expand
Coin Staircase VisualizationInput: n = 8 coins1Row 123Row 2456Row 3????Row 4 (Incomplete)Solution Steps1. Row 1: Use 1 coin (7 left)2. Row 2: Use 2 coins (5 left)3. Row 3: Use 3 coins (2 left)4. Row 4: Need 4 coins (only 2 left)Total complete rows: 3Coins used: 1 + 2 + 3 = 6Coins remaining: 8 - 6 = 2Mathematical insight:Sum of first k integers = k(k+1)/2
Understanding the Visualization
1
Start with coins
You have n coins to arrange
2
Build row by row
Each row i needs exactly i coins
3
Count complete rows
Stop when you don't have enough coins for the next row
4
Return the count
The number of complete rows is your answer
Key Takeaway
🎯 Key Insight: The problem reduces to finding the largest k where k(k+1)/2 ≤ n. We can solve this using binary search for O(log n) efficiency or directly with the quadratic formula.

Time & Space Complexity

Time Complexity
⏱️
O(√n)

We iterate through approximately √n rows since the sum 1+2+...+k = k(k+1)/2 ≈ n, so k ≈ √(2n)

n
2n
Linear Growth
Space Complexity
O(1)

Only using a few variables to track current state

n
2n
Linear Space

Constraints

  • 1 ≤ n ≤ 231 - 1
  • Note: Be careful of integer overflow when calculating triangular numbers
  • The answer will always fit in a 32-bit integer
Asked in
Amazon 15 Google 12 Microsoft 8 Apple 5
45.2K Views
Medium Frequency
~15 min Avg. Time
1.9K 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