C++ 0441.cpp
class Solution {
public:
int arrangeCoins(int n) {
int64_t step = 0;
int64_t available = 0;
while (available < n)
{
step++;
available += step;
}
if (n < available)
step--;
return step;
}
};
Difficulty
and has an acceptance rate of about 48% (1+ million submissions).
Typical patterns to solve this problem:
- Binary Search
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic “arrange coins” problem: given a total number of coins n, determine the maximum number of complete rows that can be formed when the first row contains one coin, the second row two coins, and so on. The algorithm iteratively builds rows until the cumulative count reaches or exceeds the target, then adjusts the result if an overshoot occurred. It uses 64-bit integers to safely handle large inputs and returns the final row count as a standard 32-bit integer.
Key Steps
The method begins by initializing two 64-bit counters:
int64_t step = 0;
int64_t available = 0;
step represents the current row index (the number of coins that would be placed in the next row), while available accumulates the total number of coins used so far.
The core of the algorithm is a while loop that continues as long as the accumulated coins are fewer than the input n:
while (available < n)
{
step++;
available += step;
}
Inside the loop, step is incremented to represent the next row, and that row’s coin count is added to available. This process repeats until available meets or exceeds n.
After the loop terminates, a conditional check determines whether the last addition overshot the target:
if (n < available)
step--;
If the total coins used (available) exceed the supplied amount (n), the algorithm decrements step to discard the incomplete final row, ensuring the returned value reflects only fully formed rows.
Finally, the method returns the computed row count, implicitly converting the 64-bit step back to a 32-bit int:
return step;
Edge Cases Handled
The use of int64_t for both step and available guarantees correct behavior when n approaches the upper limits of a 32-bit signed integer. For very small inputs, such as n = 0 or n = 1, the loop condition available < n correctly prevents any iteration for n = 0, leaving step at zero, which is the appropriate result. For n = 1, the loop runs once, step becomes 1, available becomes 1, and the subsequent overshoot check does not trigger, yielding a correct result of one row.
When n is exactly the sum of the first k natural numbers, the loop stops with available == n. The overshoot condition n < available evaluates to false, so step remains at k, correctly reporting the full number of rows without unnecessary adjustment.
If n falls between two triangular numbers, the loop will exceed n on the iteration that would create the next row. The conditional decrement then removes that incomplete row, delivering the largest k such that the sum of the first k numbers does not surpass n.
Performance Optimizations
The algorithm operates with a single linear pass over the potential row count. By incrementally adding the next row size to a running total, it avoids recomputing triangular numbers from scratch on each iteration, which would be more costly. The use of simple arithmetic (step++ and available += step) ensures minimal overhead per loop cycle.
Choosing 64-bit integers eliminates the need for overflow checks within the loop, allowing the addition to proceed without branching or extra logic. This design choice keeps the hot loop tight and enables the compiler to generate efficient machine code.
The final conditional adjustment (if (n < available) step--;) is executed at most once, after the loop completes, adding negligible cost while guaranteeing correctness for the overshoot scenario. Overall, the implementation balances simplicity with sufficient safeguards to handle the full range of valid inputs efficiently.
ELI5 - Simplified Explanation
Imagine building a little pyramid out of shiny blocks. You have a big pile of blocks and you want to see how many rows you can make. For the top row, you put down one block. For the second row, you put down two blocks. For the third row, you put down three blocks. You keep adding rows one by one until you run out of blocks.
The code starts by looking at your pile. It has two helpers. One helper counts which row you are currently building, and the other helper keeps track of the total number of blocks you have used so far. The code uses a loop to keep building rows as long as the total number of blocks used is still smaller than the number of blocks you started with. Inside that loop, it adds one row to the counter and then adds that number of blocks to the total pile being used.
Sometimes, you might try to build a full row but you realize you do not have quite enough blocks left to finish it. When that happens, the code notices that you used more blocks than you actually had. To fix this, it takes that last incomplete row away so that you only count the rows that were finished perfectly. After all that checking, the code knows exactly how many full rows you were able to stack up.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | |||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality