Maximum Number of Balls in a Box — LeetCode 1742 Python Solution
- Problem
- #1742
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number.
Example
- Input
- lowLimit = 1, highLimit = 10
- Output
- 2
- Explanation
- Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...
Python solution
class Solution:
def countBalls(self, lowLimit: int, highLimit: int) -> int:
cnt = [0] * 50
for x in range(lowLimit, highLimit + 1):
y = 0
while x:
y += x % 10
x //= 10
cnt[y] += 1
return max(cnt)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log_{10}m) |
| Space | O(n) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1742. Maximum Number of Balls in a Box is filed here because LeetCode tags it Math, which is the vocabulary this hub collects.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1742. Maximum Number of Balls in a Box?
- LeetCode 1742. Maximum Number of Balls in a Box is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1742. Maximum Number of Balls in a Box?
- The Python solution on this page runs in O(n \times \log_{10}m).
- What is the space complexity of LeetCode 1742. Maximum Number of Balls in a Box?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1742. Maximum Number of Balls in a Box cover?
- LeetCode 1742. Maximum Number of Balls in a Box is tagged Hash Table, Math and Counting on LeetCode.