Problem Description
An integer x is numerically balanced if for every digit d in x, the digit d appears exactly d times. Given an integer n, return the smallest numerically balanced number strictly greater than n.
Key Insights
- A number is numerically balanced if for every unique nonzero digit d, its frequency in the number is exactly d.
- Since digits are from 1 to 9, if digit d is included in the number, it must occur exactly d times.
- Any numerically balanced number can be viewed as a multiset composed of digits d where each d appears d times.
- Rather than checking every number after n, we can generate all candidate balanced numbers by considering every non-empty subset of {1, 2, …, 9} and forming the smallest permutation (by sorting) from the multiset.
- Because n is at most 10^6, the list of candidate balanced numbers generated (which is very limited in count) can be precomputed and then searched to find the smallest candidate > n.
Space and Time Complexity
Time Complexity: O(1)
(Since there are at most 2^9−1 = 511 subsets and each candidate is computed in constant time, the overall candidate list is fixed and independent from n.)
Space Complexity: O(1)
(The space used for storing the list of candidates is fixed and small.)
Solution
We solve the problem by precomputing all numerically balanced numbers. For each non-empty subset of digits from 1 to 9, if a subset S is chosen then the balanced number is formed by adding each digit d exactly d times. The smallest numeric value that can be formed from that multiset is obtained by sorting the digits in increasing order. Once we have the list of all such candidate numbers, we sort the list and find the first candidate that is strictly greater than n.
Key data structures and steps:
- Use an array (or list) to store candidate numbers.
- Use bitmask or recursion/backtracking to generate each non-empty subset of {1,2,...,9}.
- For each subset, for every digit d in the subset, append the character representation of d repeated d times.
- Sort the digits in the assembled list to get the smallest number from those digits.
- Convert the sorted string to an integer candidate.
- Finally, sort all candidates and return the first candidate greater than n.
A careful point is ensuring that we use only digits 1 through 9 (digit 0 is not considered because including it would require 0 occurrences, which is contradictory).