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 Number INPUT Given integer n: 1 Find smallest balanced number greater than n Balanced Number Rule: Each digit d appears exactly d times Example: 22 has two 2s Example: 333 has three 3s ALGORITHM STEPS 1 Generate Patterns Pre-compute all valid balanced combinations 2 Check Candidates Start from n+1, check each number 3 Validate Balance Count digits, verify d appears d times 4 Return First Valid Return smallest number that passes validation Checking Process: n=1: Not balanced 2: Not balanced (one 2) 22: Balanced! (two 2s) OK FINAL RESULT Smallest balanced number greater than 1: 22 Verification: 22 contains digit 2 Digit 2 appears 2 times Output: 22 Key Insight: Numerically balanced numbers follow strict patterns. For small inputs, only specific combinations are valid: 1, 22, 122, 333, 1333, 4444, etc. The pattern-based approach pre-generates these valid numbers, making the search efficient without brute force checking. TutorialsPoint - Next Greater Numerically Balanced Number | Pattern-Based Generation
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