Leetcode 402: Remove K Digits

grid47
grid47
Exploring patterns and algorithms
Sep 27, 2024 6 min read

A string of digits where each one is gently erased one by one, leaving the smallest number behind, glowing softly.
Solution to LeetCode 402: Remove K Digits Problem

Given a string num representing a non-negative integer and an integer k, remove k digits from num such that the remaining number is the smallest possible integer.
Problem
Approach
Steps
Complexity
Input: You are given a string num representing a non-negative integer and an integer k.
Example: For num = "35241" and k = 2, the output should be "241".
Constraints:
• 1 <= k <= num.length <= 10^5
• num consists of only digits.
• num does not contain leading zeros except for the zero itself.
Output: Return the smallest number possible after removing k digits.
Example: For num = "100005" and k = 3, the output should be "5".
Constraints:
Goal: The goal is to remove k digits from num such that the remaining number is as small as possible.
Steps:
• 1. Initialize an empty stack to hold the digits of the resulting number.
• 2. Iterate through the digits of num, comparing each digit with the top of the stack.
• 3. If the current digit is smaller than the stack's top, pop digits from the stack until the current digit is no longer smaller or k removals are reached.
• 4. After processing all digits, if any removals are left, pop the remaining digits from the stack.
• 5. Convert the stack into the final number, ensuring no leading zeros remain.
Goal: The input satisfies the following constraints:
Steps:
• 1 <= k <= num.length <= 10^5
• num consists of only digits.
• num does not contain leading zeros except for the zero itself.
Assumptions:
• The input is always valid and the given k is not greater than the length of num.
Input: For num = "35241" and k = 2, remove the digits '3' and '5' to get "241".
Explanation: Removing digits from left to right ensures that we minimize the number by removing larger digits first.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus