#1742
Maximum Number of Balls in a Box
EasyHash TableMathCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of using a dictionary, we can use a fixed-size array since the maximum possible digit sum for numbers up to 100,000 is 45 (when all digits are 9). This reduces overhead and improves performance.
⚙️
Algorithm
4 steps- 1Step 1: Initialize an array of size 46 (0 to 45) to count balls in boxes.
- 2Step 2: For each number from lowLimit to highLimit, calculate the sum of its digits.
- 3Step 3: Increment the count for the corresponding index in the array.
- 4Step 4: Return the maximum value from the array.
solution.py8 lines
1# Full working Python code
2def countBalls(lowLimit, highLimit):
3 box_count = [0] * 46
4 for num in range(lowLimit, highLimit + 1):
5 digit_sum = sum(int(digit) for digit in str(num))
6 box_count[digit_sum] += 1
7 return max(box_count)
8ℹ
Complexity note: The time complexity is O(n) because we iterate through each number once and compute the sum of digits in constant time, while the space complexity is O(1) since the array size is fixed at 46.
- 1The sum of digits for numbers in a specific range can be calculated efficiently using a simple loop.
- 2Using an array instead of a dictionary for counting can significantly reduce overhead and improve performance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.