Taro Logo

Remove K Digits

#4 Most AskedMedium
0 views
Topics:
StacksGreedy AlgorithmsStrings

Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.

Example 1:

Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.

Example 2:

Input: num = "10200", k = 1
Output: "200"
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.

Example 3:

Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and it is left with nothing which is 0.

Constraints:

  • 1 <= k <= num.length <= 105
  • num consists of only digits.
  • num does not have any leading zeros except for the zero itself.

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 length of the string `num`, and what is the maximum possible value of `k` relative to the length of `num`?
  2. How should we handle leading zeros in the resulting number after removing digits, and should the final output be represented as a string or an integer?
  3. Is it possible that `k` is equal to the length of `num`, and if so, what should the expected output be (e.g., an empty string or "0")?
  4. Can the input string `num` already contain leading zeros?
  5. If the resulting number becomes empty after removing digits, what should be returned?

Brute Force Solution

Approach

Imagine you have a long number and you need to erase a specific amount of digits to make the remaining number as small as possible. The brute force approach involves exploring every single possible combination of digits you could choose to erase.

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

  1. Start by looking at the original number.
  2. Systematically find every single way to remove the target quantity of digits by picking different combinations.
  3. Write down or remember the resulting smaller number for each of those combinations.
  4. Once you have generated every possible remaining number, compare them all side by side.
  5. Select the absolute smallest number from your complete collection of possibilities as your final answer.

Code Implementation

import itertools


def remove_k_digits_brute_force(num_string, digits_to_remove):
    # Generate all unique index combinations to ensure we check every removal possibility
    index_combinations = itertools.combinations(
        range(len(num_string)), len(num_string) - digits_to_remove
    )

    possible_numbers = []

    for current_combination in index_combinations:
        constructed_number = "".join(num_string[index] for index in current_combination)
        possible_numbers.append(constructed_number)

    # Filter out leading zeros and handle empty string edge case for proper numeric comparison
    cleaned_numbers = [
        number.lstrip("0") if number.lstrip("0") else "0" for number in possible_numbers
    ]

    # Sort numerically based on length first then string value to correctly find the absolute minimum
    cleaned_numbers.sort(key=lambda item: (len(item), item))

    # Return the absolute smallest number from our complete collection of possibilities
    return cleaned_numbers[0] if cleaned_numbers else "0"

Big(O) Analysis

Time Complexity
O(n * C(n, k)) – To find the smallest number, the brute force approach generates every possible combination of removing k digits from the n total digits of the number. There are C(n, k) such combinations, and for each combination, we must construct and compare strings of length approximately n minus k. This leads to approximately C(n, k) * n operations, which dominates the total execution time. As the input size n and removals k grow, this exponential-like growth makes the approach extremely costly compared to linear solutions.
Space Complexity
O(N) – To find the smallest number, the optimal stack-based approach utilizes a character array or string builder to maintain the remaining digits during the iteration. In the worst-case scenario where no digits are removed, this auxiliary storage grows linearly up to size N, where N is the length of the input number string. Additionally, a few primitive variables are used for loop control and counting, which require constant extra space. Therefore, the total extra memory scales directly with the input size N, resulting in a linear space complexity.

Optimal Solution

Approach

To find the smallest possible number after removing a specific amount of digits, we want to build our answer from left to right while keeping the smaller digits as far left as possible. We can achieve this by comparing each new digit to the ones we have already kept and tossing out larger digits if a smaller one comes along.

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

  1. Create a holding space to keep track of the digits we decide to keep in order.
  2. Look at each digit of the number one by one, moving from left to right.
  3. Whenever the current digit is smaller than the last digit we placed in our holding space, remove that last digit from our holding space because having a smaller digit earlier makes the whole number smaller.
  4. Repeat this removal process for any previous digits that are larger than the current one, stopping when we run out of removals to spend or when the digits in our holding space are already smaller than or equal to the current one.
  5. Add the current digit to our holding space.
  6. After looking at every digit, if we still have allowed removals left to spend, take them from the end of our holding space since those are the rightmost and least important digits.
  7. Clean up any leading zeros that might have ended up at the very front of our holding space, and reveal the final smallest number.

Code Implementation

def remove_k_digits(numeric_string, digits_to_remove):
    holding_space = []

    for current_digit in numeric_string:
        # Remove larger previous digits so smaller digits occupy more significant left positions.
        while digits_to_remove > 0 and holding_space and holding_space[-1] > current_digit:
            holding_space.pop()
            digits_to_remove -= 1

        holding_space.append(current_digit)

    # If removals remain, trim from the right since those are the largest magnitude digits.
    if digits_to_remove >:
        holding_space = holding_space[:-digits_to_remove]

    final_number_string = "".join(holding_space).lstrip("0")

    # Return zero if the string became empty after trimming leading zeros and digits.
    return final_number_string if final_number_string else "0"

Big(O) Analysis

Time Complexity
O(n) – As we iterate through each of the n digits of the input string from left to right, we push and pop them from our holding space stack. Each digit is pushed onto the stack at most once and popped at most once during the comparison and removal steps. Therefore, the total number of stack operations is bounded by 2n, which scales linearly with the input size. This leads to approximately 2n operations, simplifying to O(n).
Space Complexity
O(N) – The holding space, implemented as a stack or list to store the kept digits, grows proportionally with the input size. In the worst-case scenario where no digits are removed during the iteration, this holding space will store all N digits from the input string. A few auxiliary pointer and counter variables are also used, but their memory footprint remains constant. Therefore, the total extra memory consumed scales linearly with N, simplifying to Big O of N.

Edge Cases

Removing all digits where k equals the length of num
How to Handle:
Return a zero string since removing every digit leaves nothing, and an empty result should default to 0.
Removing zero digits where k is 0
How to Handle:
Return the original string as no digits need to be removed.
Leading zeros in the resulting number after removals
How to Handle:
Strip all leading zeros from the final accumulated stack before returning, ensuring standard integer representation.
Monotonically increasing digits like 12345 with k equals 2
How to Handle:
The greedy stack approach will naturally pop the largest elements from the end of the string.
Monotonically decreasing digits like 54321 with k equals 2
How to Handle:
The monotonic stack continuously pops larger elements until k runs out, leaving the smallest remaining suffix.
All digits are identical such as 1111 with k equals 2
How to Handle:
The algorithm removes the first k digits from the left since no smaller predecessor exists to trigger a pop.
String length is at the maximum constraint limit of 100000
How to Handle:
A linear time stack-based approach processes the string in O(N) time to efficiently scale within time limits.
Resulting string becomes completely empty after stripping leading zeros
How to Handle:
Return a single zero character to satisfy the requirement that the output represents a valid non-negative integer.
0/8 completed