Maximum Number of Balls in a Box - Problem

Imagine you're working at a magical ball factory! 🏭 You have n balls numbered consecutively from lowLimit to highLimit (inclusive), and an infinite number of boxes numbered from 1 to infinity.

Your job is to sort these balls into boxes using a special rule: each ball goes into the box whose number equals the sum of the ball's digits.

Examples of the sorting rule:

  • Ball 321 → Box 3 + 2 + 1 = 6
  • Ball 10 → Box 1 + 0 = 1
  • Ball 999 → Box 9 + 9 + 9 = 27

After sorting all balls, you need to find which box contains the maximum number of balls and return that count.

Goal: Return the number of balls in the most crowded box!

Input & Output

example_1.py — Small Range
$ Input: lowLimit = 1, highLimit = 10
Output: 2
💡 Note: Balls 1→box 1, 2→box 2, 3→box 3, 4→box 4, 5→box 5, 6→box 6, 7→box 7, 8→box 8, 9→box 9, 10→box 1. Box 1 has balls [1,10], so count is 2.
example_2.py — Medium Range
$ Input: lowLimit = 5, highLimit = 15
Output: 2
💡 Note: Balls: 5→box 5, 6→box 6, 7→box 7, 8→box 8, 9→box 9, 10→box 1, 11→box 2, 12→box 3, 13→box 4, 14→box 5, 15→box 6. Box 5 has balls [5,14] and box 6 has balls [6,15], both with count 2.
example_3.py — Single Ball
$ Input: lowLimit = 19, highLimit = 19
Output: 1
💡 Note: Only one ball (19) which goes to box 1+9=10. That box contains 1 ball, so the answer is 1.

Visualization

Tap to expand
🏭 Ball Factory Sorting Process123456789SCANSCANSCAN1+2+3=64+5+6=157+8+9=24Box 6Count:1Box 15Count:1Box 24Count:1Control PanelMax Count: 1Balls Processed: 3Active Boxes: 3Status: Optimal ✓
Understanding the Visualization
1
Scan Ball Number
Each ball passes through a scanner that reads its number
2
Calculate Digit Sum
The system calculates the sum of all digits in the ball number
3
Route to Box
Ball is automatically routed to the box matching its digit sum
4
Update Counter
Box counter increments and system tracks if this is the new maximum
Key Takeaway
🎯 Key Insight: Process each ball exactly once, immediately updating both the frequency count and maximum tracker for optimal O(n×d) performance!

Time & Space Complexity

Time Complexity
⏱️
O(n × d)

Where n is the number of balls (highLimit - lowLimit + 1) and d is the average number of digits per number. Each ball is processed exactly once.

n
2n
Linear Growth
Space Complexity
O(k)

Where k is the number of unique digit sums (at most 45 for 5-digit numbers). We store one entry per unique box.

n
2n
Linear Space

Constraints

  • 1 ≤ lowLimit ≤ highLimit ≤ 105
  • Ball numbers are consecutive integers
  • Box numbers start from 1 (minimum possible digit sum)
  • Maximum possible digit sum is 45 (for number 99999)
Asked in
Google 25 Amazon 18 Microsoft 12 Meta 8
28.4K Views
Medium Frequency
~15 min Avg. Time
980 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen