Input: n =1Output: 22Explanation:
22is numerically balanced since:- The digit 2 occurs 2 times.It is also the smallest numerically balanced number strictly greater than 1.
Input: n =1000Output: 1333Explanation:
1333is numerically balanced since:- The digit 1 occurs 1 time.- The digit 3 occurs 3 times.It is also the smallest numerically balanced number strictly greater than 1000.Note that 1022 cannot be the answer because 0 appeared more than 0 times.
Input: n =3000Output: 3133Explanation:
3133is numerically balanced since:- The digit 1 occurs 1 time.- The digit 3 occurs 3 times.It is also the smallest numerically balanced number strictly greater than 3000.
Numerically balanced numbers are rare and have a specific digit frequency pattern. Since n ≤ 10^6, we can enumerate all possible candidates up to a reasonable upper bound and pick the smallest one greater than n.
Generate all numbers up to a certain limit (e.g., 1224444) and check if each is numerically balanced. For each number, count the frequency of each digit and verify that for every digit d > 0, the count of d is exactly d, and no digit 0 appears. Return the smallest such number greater than n.
classSolution {
private:bool isBalanced(int x) {
int cnt[10] = {};
int y = x;
while (y) { cnt[y%10]++; y /=10; }
for (int d =1; d <10; ++d) {
if (cnt[d] && cnt[d] != d) return false;
}
return cnt[0] ==0;
}
public:int nextBeautifulNumber(int n) {
for (int x = n+1; x <=1224444; ++x) {
if (isBalanced(x)) return x;
}
return-1;
}
};
classSolution {
privatefunisBalanced(x: Int): Boolean {
val cnt = IntArray(10)
var y = x
while (y > 0) {
cnt[y%10]++ y /=10 }
for (d in1..9) {
if (cnt[d] > 0&& cnt[d] != d) returnfalse }
return cnt[0] ==0 }
funnextBeautifulNumber(n: Int): Int {
for (x in n+1..1224444) {
if (isBalanced(x)) return x
}
return -1 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defnextBeautifulNumber(self, n: int) -> int:
defis_balanced(x: int) -> bool:
cnt = [0]*10 y = x
while y:
cnt[y%10] +=1 y //=10for d in range(1, 10):
if cnt[d] and cnt[d] != d:
returnFalsereturn cnt[0] ==0for x in range(n+1, 1224445):
if is_balanced(x):
return x
return-1