#2048
Next Greater Numerically Balanced Number
MediumHash TableMathBacktrackingCountingEnumerationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(1)Space O(n)
The optimal solution involves generating numerically balanced numbers directly instead of checking each number. We can build these numbers based on the properties of numerically balanced numbers, ensuring we find the smallest one greater than n efficiently.
⚙️
Algorithm
4 steps- 1Step 1: Generate numerically balanced numbers by iterating through possible digit counts (1 to 9).
- 2Step 2: For each digit d, create the number by repeating d exactly d times.
- 3Step 3: Store these generated numbers and sort them.
- 4Step 4: Find the smallest number in the sorted list that is greater than n.
solution.py17 lines
1# Full working Python code
2
3def generate_balanced_numbers():
4 balanced_numbers = []
5 for d in range(1, 10):
6 num = int(str(d) * d)
7 balanced_numbers.append(num)
8 return sorted(balanced_numbers)
9
10def next_greater_balanced(n):
11 balanced_numbers = generate_balanced_numbers()
12 for num in balanced_numbers:
13 if num > n:
14 return num
15
16# Example usage
17print(next_greater_balanced(1)) # Output: 22ℹ
Complexity note: The time complexity is O(1) for finding the next greater number because we are generating a fixed set of numerically balanced numbers (only 9 possible digits), and the search is constant time. The space complexity is O(n) due to storing the generated numbers.
- 1Numerically balanced numbers are limited to digits 1-9, as 0 cannot appear.
- 2The maximum numerically balanced number under the constraints is 999999.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.