1231. Digit Sum Leader
A lottery office labels each ticket with its digit sum: the sum of the decimal digits of its number, so ticket 4096 has digit sum 19. Tickets numbered from low to high, both included, were printed.
Return the digit sum that is shared by the largest number of printed tickets. If several digit sums share the top count, return the smallest of them. The range is never empty.
Enumerate every integer in the range, tally the digit sums in an array or hash map, and pick the best entry. Time is O((high - low + 1) * d) for d digits, and space is O(1) because digit sums stay below 50.
Example 1
- Input:
- low = 1, high = 20
- Output:
- 2
- Explanation:
Digit sum 2 is shared by 2, 11 and 20 (three numbers), more than any other sum in this range.
Example 2
- Input:
- low = 5, high = 5
- Output:
- 5
- Explanation:
The range holds only the number 5, so the leader is 5.
Example 3
- Input:
- low = 1, high = 9
- Output:
- 1
- Explanation:
Every digit sum from 1 to 9 occurs once, so the tie goes to the smallest, 1.
Constraints
1 ≤ low ≤ high ≤ 105
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O((high - low + 1) * d)
- Space
- O(1)