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
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)
✓ Linear Growth
Space Complexity
O(1)
Only using a few variables to track current state
✓ 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code