Problem overview
The function sumUntilLimit receives a positive integer limit. It adds the numbers 1, 2, 3, and so on, in that order, and stops as soon as the total is at least limit. It returns how many numbers it added. The last number counts, even if it pushes the total past the limit.
For limit = 10, 1 + 2 + 3 + 4 = 10 reaches the limit exactly, so the answer is 4. For limit = 11 the total after 4 numbers is 10, which is still below 11, so 5 is added too. The total becomes 15 and the answer is 5. For limit = 1 the first number already reaches it, so the answer is 1.
Approach
Keep two variables: total, the sum so far, and count, how many numbers have been added. Because the numbers are 1, 2, 3 in order, count is also the last number added. Each pass raises count by one and adds it to total. The loop continues while total < limit and stops the moment the total reaches the limit.
The values after each pass for limit = 11:
| Pass | count after | total after |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
| 4 | 4 | 10 |
| 5 | 5 | 15 |
After pass 4 the total, 10, is below 11, so the loop runs again. After pass 5 it is 15, the check fails, and the function returns 5.
Step by step
- Create
totalwithvar, starting at 0. It changes inside the loop, sovalwould not compile. - Create
countwithvar, starting at 0. No number has been added yet. - Loop while
total < limit. The loop ends when the total reaches or passes the limit, which is when the adding must stop. - Move to the next number:
count++. It is 1 on the first pass, 2 on the second. - Add it to the total:
total += count. The order matters:countgoes up first, so the number added is the next one in the sequence. - Return
count.
The solution in Kotlin
class Solution {
fun sumUntilLimit(limit: Int): Int {
var total = 0
var count = 0
while (total < limit) {
count++
total += count
}
return count
}
}
Some details worth knowing:
- The check happens before each pass. That is why the number that reaches the limit is still added: the loop only notices after the pass is done.
- No
Intoverflow. With the largest limit, 1000000000, the loop ends after 44721 passes. The total stays near the limit, far below theIntmaximum of 2147483647. +=and++.total += countmeanstotal = total + count, andcount++adds 1 tocount.
Complexity
The total after k numbers is about k²/2, so the loop runs roughly the square root of 2 * limit times. Time is O(√limit), and the largest input takes 44721 passes. Space is O(1).
Edge cases and common mistakes
- Stopping one number early. With
total <= limitas the condition, the loop would continue after reaching the limit exactly, andlimit = 10would give 5. - Swapping the two lines. If
total += countruns beforecount++, the first number added is 0 and the answer is off by one. - A limit of 1. The first pass reaches it, so the answer is 1, not 0.
- Returning
total. The task asks how many numbers were added, not their sum.
Testing
10gives4.11gives5.1gives1.1000000000gives44721.
