Next Greater Numerically Balanced Number - Problem

An integer x is numerically balanced if for every digit d in the number x, there are exactly d occurrences of that digit in x.

For example:

  • 122 is numerically balanced because digit 1 appears exactly 1 time, and digit 2 appears exactly 2 times.
  • 1223 is not numerically balanced because digit 1 appears 1 time, digit 2 appears 2 times, but digit 3 appears 1 time (not 3 times).

Given an integer n, return the smallest numerically balanced number strictly greater than n.

Input & Output

Example 1 — Basic Case
$ Input: n = 1
Output: 22
💡 Note: The next numerically balanced number after 1 is 22, where digit 2 appears exactly 2 times.
Example 2 — Find Next Pattern
$ Input: n = 1000
Output: 1333
💡 Note: After 1000, the next balanced number is 1333, where digit 1 appears 1 time and digit 3 appears 3 times.
Example 3 — Already Large
$ Input: n = 3000
Output: 3133
💡 Note: The next balanced number is 3133, which is a permutation of digits 1 and 3 maintaining the balance property.

Constraints

  • 0 ≤ n ≤ 106

Visualization

Tap to expand
Next Greater Numerically Balanced Numbern = 1000Input→ Find next balanced →1333OutputBalanced: digit 1 appears 1 time, digit 3 appears 3 times13331333 > 1000 and is numerically balanced
Understanding the Visualization
1
Input
Given number n
2
Process
Find next number where each digit d appears d times
3
Output
Smallest balanced number > n
Key Takeaway
🎯 Key Insight: Only specific digit patterns can form balanced numbers, making precomputed lookup the most efficient solution
Asked in
Google 25 Meta 18
12.5K Views
Medium Frequency
~15 min Avg. Time
456 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