VOOZH about

URL: https://www.geeksforgeeks.org/dsa/build-lowest-number-by-removing-n-digits-from-a-given-number/

⇱ Lowest Number by Removing k digits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Lowest Number by Removing k digits

Last Updated : 2 Apr, 2026

Given a string s of digits and an integer k, remove k digits from s to form the smallest possible number while keeping the order of the remaining digits. The resulting string should not have leading zeros and if it becomes empty, return "0".

Examples:

Input: s = "4325043", k = 3
Output: "2043"
Explanation: By removing three digits (4, 3, 5) while preserving the order of the remaining digits, we obtain "2043", which is the smallest possible number.

Input: s = "765028321", k = 5
Output: "221"
Explanation: Removing five digits (7, 6, 5, 8, 3) results in "0221". Since the number should not contain leading zeros, the final answer is "221".

[Naive Approach] Iterative Greedy Removal - O(n*k) Time and O(n) Space

We run two nested loop where the outer loops runs through the current string and the inner loop removes the first digit that is greater than its next digit, since removing a larger digit earlier leads to a smaller number. If no such digit exists, remove the last digit.


Output
221

[Better Approach] Using Stack - O(n) Time and O(n) Space

We use a stack to build the smallest number by maintaining digits in increasing order. For each digit, we remove up to k larger digits from the stack before pushing the current one. This ensures smaller digits appear earlier while preserving the original order.

Illustration of the example using stack based approach:

Below is the implementation of the above approach.


Output
221

[Expected Approach] In-Place Digit Removal - O(n) Time and O(1) Space

We treat the input string as a stack using a pointer top. For each digit, we overwrite the previous digits if they are larger and we still have digits to remove (k > 0). This builds the smallest number in-place while avoiding extra memory. Remaining digits are trimmed from the end, and leading zeros are skipped.


Output
221
Comment