Taro Logo

Next Greater Numerically Balanced Number

#12 Most AskedMedium
0 views
Topics:
Recursion

An integer x is numerically balanced if for every digit d in the number x, there are exactly d occurrences of that digit in x.

Given an integer n, return the smallest numerically balanced number strictly greater than n.

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

  • 0 <= n <= 106

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum possible value for the input integer $n$?
  2. Are negative numbers or zero possible inputs, and how should they be handled?
  3. Is it guaranteed that a numerically balanced number always exists within standard integer limits for any valid input $n$?
  4. Can the definition of a numerically balanced number include single-digit numbers like 1?
  5. Should the result be returned as an integer, or is a string representation preferred in case the number exceeds standard integer limits?

Brute Force Solution

Approach

The problem asks for the smallest integer strictly greater than a given number that is numerically balanced. In a numerically balanced number, every digit appears a number of times equal to its value, and the digit zero cannot appear. Given the upper bound on the input, we can sequentially check consecutive integers starting from the next number until a valid balanced number is found.

Here's how the algorithm would work step-by-step:

  1. Initialize the candidate value to the given integer plus one.
  2. Implement a helper function to verify if any number satisfies the numerically balanced condition.
  3. Within the helper, count the frequency of each digit and immediately reject numbers containing zero.
  4. Ensure that every distinct digit in the frequency map matches its occurrence count.
  5. Loop continuously, testing each candidate number using the helper.
  6. Increment the candidate by one in each iteration until the balanced condition is met.
  7. Return the first balanced candidate found.

Code Implementation

def next_beautiful_number(n: int) -> int:
    # Define a helper function to check if a number is numerically balanced.
    def is_balanced(candidate: int) -> bool:
        digit_counts = {}
        temp_value = candidate
        while temp_value > 0:
            digit = temp_value % 10
            if digit == 0:
                return False
            digit_counts[digit] = digit_counts.get(digit, 0) + 1
            temp_value //= 10
        # Verify that each digit appears exactly as many times as its numerical value.
        for digit, count in digit_counts.items():
            if digit != count:
                return False
        return True

    current_number = n + 1
    # Increment the number sequentially until a balanced number is encountered.
    while not is_balanced(current_number):
        current_number += 1
    return current_number

Big(O) Analysis

Time Complexity
O(M * D) – Here M is the difference between the resulting balanced number and n, and D is the number of digits in the candidates tested (at most 7). Because the next numerically balanced number is never far from n (the maximum answer for n <= 10^6 is 1224444), M is small and the search terminates very quickly.
Space Complexity
O(D) – The helper function uses a frequency map that holds at most D unique digits, where D is the number of digits (at most 7 for numbers up to 1224444).

Optimal Solution

Approach

To find the next numerically balanced number, we can take advantage of the fact that these special numbers are surprisingly rare and have a strict upper limit. Instead of guessing randomly or searching infinitely, we can simply check every number starting from the given starting point until we find the very first one that satisfies the balance rule.

Here's how the algorithm would work step-by-step:

  1. Begin with the number you are given in the problem.
  2. Check the current number to see if it is numerically balanced by counting how many times each digit appears.
  3. Verify if every digit present in the number matches its own frequency exactly, and ensure no other digits are present.
  4. If the number is balanced, you have found your answer and can stop.
  5. If the number is not balanced, move forward by one to the next whole number.
  6. Repeat the checking process on this new number and continue stepping forward until a balanced number is reached.

Code Implementation

class Solution:
    def nextBeautifulNumber(self, starting_integer: int) -> int:
        current_candidate = starting_integer + 1

        # We iterate sequentially because balanced numbers are sparse and bounded within a small range.
        while True:
            digit_frequency_map = {}

            for current_digit_char in str(current_candidate):
                digit_frequency_map[current_digit_char] = digit_frequency_map.get(current_digit_char, 0) + 1

            is_balanced_number = True

            for digit_char, frequency in digit_frequency_map.items():
                if int(digit_char) != frequency:
                    is_balanced_number = False
                    break

            # Halting early guarantees we return the very first valid balanced number encountered.
            if is_balanced_number:
                return current_candidate

            current_candidate += 1

Big(O) Analysis

Time Complexity
O(1) – The algorithm sequentially checks integers starting from n to find the next numerically balanced number. Because numerically balanced numbers are extremely sparse and strictly bounded by the problem constraints, the maximum number of checks required is a fixed constant. Therefore, the total operations do not scale with the input size n, bounding the execution time to a constant time complexity of O(1).
Space Complexity
O(1) – To check if a number is numerically balanced, the algorithm extracts its individual digits and stores their frequencies using a fixed-size frequency array of length 10 or a small hash map. Since the maximum possible number of digits for any valid balanced number within the constraints is bounded by a small constant (specifically 7 digits, as the largest balanced number is 1224444), the memory consumed by these data structures does not scale with the input integer N. Furthermore, incrementing and checking the numbers requires only a few primitive integer variables. Therefore, the auxiliary space remains entirely constant regardless of the magnitude of the starting number.

Edge Cases

Input n is already a numerically balanced number
How to Handle:
The algorithm should immediately recognize this and return n without incrementing.
Input n is 0 or negative
How to Handle:
Since the problem implies positive integers and the smallest valid number is 1, our search should start at max(1, n).
Extremely large inputs approaching the maximum value constraint
How to Handle:
We must ensure the search space remains small since the largest possible balanced number within standard constraints is 122444.
Single-digit inputs like n = 1
How to Handle:
The algorithm correctly evaluates 1 since the digit 1 appears exactly 1 time.
Inputs requiring crossing a digit-length boundary
How to Handle:
The search will naturally check numbers of increasing lengths up to 7 digits where a balanced number is guaranteed to exist.
Inputs with digits whose frequencies do not match their values
How to Handle:
A frequency counting helper function verifies each candidate number digit by digit before returning.
Integer overflow during brute force incrementation
How to Handle:
Using 64-bit integer types prevents overflow since the maximum possible answer fits well within standard integer limits.
Performance overhead from linear scanning of every integer
How to Handle:
Given the small upper bound of valid balanced numbers, a simple iterative check from n upwards performs efficiently within time limits.
0/45 completed