2048. Next Greater Numerically Balanced Number

time : O(n*logn), n is the max input,

space: O(1)

// brute force, time : O(n*logn), n is the max input, space: O(1)
class Solution {
    public int nextBeautifulNumber(int n) {
        while (true) {
            n++;
            if (isValid(n)) {
                return n;
            }
        }
    }
    private boolean isValid(int n) {
        int count[] = new int[10];
        while (n != 0) {
            if (n % 10 == 0) { // in this problem, the ans wont has 0 in each single digits, 0 cant appear 0 time
                return false;
            }
            count[n%10]++; // count digits' number
            n /= 10;
            
        }
        for (int i = 1; i < 10; i++) {
            if (count[i] != 0 && count[i] != i) { // as problem discription, digit i occurs i times
                return false;
            }
        }
        return true;
    }
}

/*
> n

start from n to find beauti number

Brute force



*/j

Last updated