Skip to main content
Back to problems
#2048
Medium Algorithms

Next greater numerically balanced number

Hash Table Math Backtracking Counting Enumeration
63.0% acceptance
Feb 25, 2026
553
375
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. Given an integer n, return the smallest numerically balanced number strictly greater than n.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn next_beautiful_number(n: i32) -> i32 {
    fn is_balanced(x: i32) -> bool {
      let mut cnt = [0i32; 10];
      let mut tmp = x;
      while tmp > 0 {
        cnt[(tmp % 10) as usize] += 1;
        tmp /= 10;
      }
      for d in 0..10 {
        if cnt[d] > 0 && cnt[d] != d as i32 {
          return false;
        }
      }
      true
    }
    let mut x = n + 1;
    while !is_balanced(x) {
      x += 1;
    }
    x
  }
}