LeetCode Entry
2048. Next Greater Numerically Balanced Number
First bigger number freq[digit]=digit
2048. Next Greater Numerically Balanced Number medium blog post substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1152
Problem TLDR
First bigger number freq[digit]=digit #medium
Intuition
Brute-force is accepted. For the problem size of 10^6 the next value is 1224444 which is just 200k loop.
Approach
- or we can try to generate all permutations; prune by length of the initial number
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(1)\)
Code
// 425ms
fun nextBeautifulNumber(n: Int) = (n+1..n*21+1)
.first { "$it".groupBy { it }.all { it.key-'0' == it.value.size }}
// 22ms
pub fn next_beautiful_number(n: i32) -> i32 {
(n+1..n*22+2).find(|&x| { let (mut y,mut f) = (x, [0;10]);
while y > 0 { f[(y%10)as usize] += 1; y /= 10 }
(0..=9).all(|x| f[x] == x || f[x] < 1)
}).unwrap()
}