<p>An integer <code>x</code> is <strong>numerically balanced</strong> if for every digit <code>d</code> in the number <code>x</code>, there are <strong>exactly</strong> <code>d</code> occurrences of that digit in <code>x</code>.</p>

<p>Given an integer <code>n</code>, return <em>the <strong>smallest numerically balanced</strong> number <strong>strictly greater</strong> than </em><code>n</code><em>.</em></p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 22
<strong>Explanation:</strong> 
22 is numerically balanced since:
- The digit 2 occurs 2 times. 
It is also the smallest numerically balanced number strictly greater than 1.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 1000
<strong>Output:</strong> 1333
<strong>Explanation:</strong> 
1333 is 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.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> n = 3000
<strong>Output:</strong> 3133
<strong>Explanation:</strong> 
3133 is 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.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>0 &lt;= n &lt;= 10<sup>6</sup></code></li>
</ul>

# class Solution:
#     def nextBeautifulNumber(self, n: int) -> int:
#         max_digits = [1, 22, 333, 4444, 55555, 666666, 7777777]
#         min_digits = [1, 22, 122, 1333, 22333, 122333, 1224444]
#         ln = len(str(n))
#         d = defaultdict(set)
#         def dfs(s, i):
#             if i == 0:
#                 #print(f"s = {s}")
#                 d[len(s)].update(int("".join(p)) for p in permutations(s) if p)
#                 return
            
#             used = set()
#             for x in max_digits:
#                 if x not in used:
#                     used.add(x)
#                     dfs(s+str(x), i-len(str(x)))
#                     used.remove(x)
#             return
                
#         if n >= max_digits[ln-1]:
#             return min_digits[ln]
#         else:
#             for k in range (ln+1):
#                 dfs("", k)
#             ls = list(d[ln]).sort()
#             idx = bisect_right(ls, n)
            
#             return ls[idx]
class Solution:
    def nextBeautifulNumber(self, n: int) -> int:
        for x in count(n + 1):
            y = x
            cnt = [0] * 10
            while y:
                y, v = divmod(y, 10)
                cnt[v] += 1
            if all(v == 0 or i == v for i, v in enumerate(cnt)):
                return x
2929