You are working in a ball factory where you have n
balls numbered from lowLimit
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 whose number is equal to the sum of the digits of the ball’s number. For example, the ball number 321 will belong to the box number 3 + 2 + 1 = 6
.
Given two integers lowLimit
and highLimit
, return the number of balls in the box with the most balls.
lowLimit
and highLimit
, or can they be any integer within Python’s integer range?
lowLimit
, highLimit
≤ 10^5).To solve this problem, we can follow these steps:
lowLimit
to highLimit
, compute the box number using the digit sum, and count how many balls go into each box.def countBalls(lowLimit: int, highLimit: int) -> int:
from collections import defaultdict
def digit_sum(num: int) -> int:
return sum(int(digit) for digit in str(num))
box_count = defaultdict(int)
for ball in range(lowLimit, highLimit + 1):
box_number = digit_sum(ball)
box_count[box_number] += 1
return max(box_count.values())
# Example usage:
lowLimit = 1
highLimit = 10
# Expected output: 2 (because box 1 has balls 1 and 10)
print(countBalls(lowLimit, highLimit))
lowLimit
to highLimit
. The number of iterations is O(highLimit - lowLimit + 1), denoted as n.Overall, the time complexity of the solution is O(n * log(highLimit)), where n
is the number of balls and log(highLimit) accounts for the digit sum calculation.
This solution efficiently computes the maximum number of balls in any box by leveraging a hash map to count balls and then finds the maximum count. The helper function for digit sum ensures the code remains readable and modular.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?