Taro Logo

Remove 9

#2 Most AskedHard
0 views
Topics:
Math

Start from integer 1, remove any integer that contains 9 such as 9, 19, 29...

Now, you will have a new integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ...].

Given an integer n, return the nth (1-indexed) integer in the new sequence.

Example 1:

Input: n = 9
Output: 10

Example 2:

Input: n = 10
Output: 11

Constraints:

  • 1 <= n <= 8 * 108

Solution


Brute Force Solution

Approach

Imagine we are writing down a list of numbers in order, but we completely skip any number that contains the digit nine. The brute force approach simply inspects every single whole number starting from one, checks if it contains a nine, and keeps a tally of the valid ones until we reach our target position.

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

  1. Begin by looking at the very first whole number, which is one.
  2. Check if this number contains the digit nine anywhere inside it.
  3. If it does contain a nine, ignore it and do not add it to our special list.
  4. If it does not contain a nine, count it as part of our special list.
  5. Move on to the next whole number and repeat the checking process.
  6. Continue checking every consecutive number one by one, skipping any that have a nine.
  7. Stop as soon as our special list reaches the exact target position you asked for, and reveal the last number we added.

Code Implementation

def remove_nine_brute_force(target_position):
    valid_numbers_count = 0
    current_number = 0

    # Loop infinitely because we must check consecutive numbers until reaching the target count
    while True:
        current_number += 1

        # Convert to string to easily check for the forbidden digit without math operations
        if '9' not in str(current_number):
            valid_numbers_count += 1

            # Stop once the tally matches our target position to reveal the final number
            if valid_numbers_count == target_position:
                return current_number

Big(O) Analysis

Time Complexity
O(n * d) – To find the n-th number that skips the digit nine, we must inspect consecutive integers one by one until our valid count reaches n. For each integer we evaluate, the cost is driven by converting the number to a string or checking its digits, which takes d operations where d is the number of digits in the integer. Because the value of each integer grows roughly proportional to the target index n, we roughly check n numbers, each taking up to log10(n) steps. This leads to approximately n * log10(n) operations, which simplifies in Big O notation to O(n * log(n)) or O(n * d).
Space Complexity
O(1) – The algorithm requires a constant amount of extra memory regardless of the target position N. It only uses a few primitive variables to track the current number and maintain the count, without allocating any dynamic data structures, arrays, or recursion stacks. Therefore, the auxiliary space complexity remains strictly constant as the input grows.

Optimal Solution

Approach

Instead of checking every single number one by one to see if it contains a forbidden digit, the optimal approach translates the target position into a different counting system. By changing how we count, we can instantly jump to the correct answer without doing heavy searching.

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

  1. Realize that the problem is asking us to list numbers in order while completely skipping any number that contains the digit nine.
  2. Notice that if we write numbers in a system where each position only goes up to nine instead of ten, the pattern of available numbers changes entirely.
  3. Observe that skipping nines is mathematically identical to counting in base nine instead of our usual base ten.
  4. Take the input position given to us, which is currently written in our normal everyday counting system.
  5. Convert that position number so that it is interpreted using base nine values.
  6. The resulting converted value is magically the exact number we would get if we had manually skipped every number containing a nine.
  7. Return this converted value as the final answer immediately without needing to check any numbers in between.

Code Implementation

def new_integer_after_removal(input_position):

    # We convert the decimal index to base nine because skipping nines is identical to base nine counting.
    converted_digits = []

    current_number = input_position
    while current_number > 0:
        current_remainder = current_number % 9
        converted_digits.append(str(current_remainder))
        current_number = current_number // 9

    # Reversing is necessary because modulo operations extract digits from least to most significant.
    converted_digits.reverse()

    base_nine_string = ''.join(converted_digits)

    # Parsing as base 10 integer yields the exact value after skipping numbers containing nine.
    return int(base_nine_string or '0')

Big(O) Analysis

Time Complexity
O(log n) – The input size n represents the target position in the sequence, and the cost is driven by converting this decimal number into base nine. This conversion process relies on repeated division by nine, which reduces the magnitude of n logarithmically with each step. Since the number of division and modulo operations is proportional to the number of digits in base nine, the operations scale with the logarithm of n. Therefore, the total operations approximate log base 9 of n, which simplifies to O(log n).
Space Complexity
O(1) – The optimal solution translates the input position into base nine using only a few primitive integer variables to perform arithmetic operations like division and modulo. No auxiliary data structures, temporary lists, or recursive call stacks are utilized during this conversion process. Because the amount of extra memory remains constant regardless of the magnitude of the input integer N, the auxiliary space complexity is strictly constant.

Edge Cases

Input n equals 1, the absolute minimum positive integer.
How to Handle:
The base case correctly converts and returns 1 since it contains no 9.
Inputs containing the digit 9 such as 9, 19, or 90.
How to Handle:
The conversion algorithm treats the number space as base 9 instead of base 10 to skip all 9-containing values.
Large inputs approaching maximum integer constraints like 2 to the power of 31 minus 1.
How to Handle:
Using standard 32-bit or 64-bit integer division and modulo operations ensures efficient logarithmic time scaling without overflow.
Zero or negative inputs which fall outside the positive integer domain.
How to Handle:
The problem statement specifies positive integers, so inputs start strictly at 1 and upward.
Boundary numbers transitioning across decades where digits shift like 8 to 10 or 89 to 100.
How to Handle:
Repeated modulo 9 operations correctly handle base shifting to bypass the digit 9 seamlessly.
0/2 completed