Skip to content

402. Remove K Digits #144

Answered by mah-shamim
mah-shamim asked this question in Q&A
Jul 30, 2024 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

We can use a greedy approach with a stack. The goal is to build the smallest possible number by iteratively removing digits from the given number while maintaining the smallest possible sequence.

Approach:

  1. Use a Stack: Traverse through each digit of the number. Push digits onto a stack while ensuring that the digits in the stack form the smallest possible number.
  2. Pop from Stack: If the current digit is smaller than the top of the stack, and we still have k digits to remove, pop the stack to remove the larger digits.
  3. Handle Remaining Digits: If there are still digits to remove after processing all the digits in num, remove them from the end of the stack.
  4. Build the Result: Construct the fi…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Aug 28, 2024
Collaborator

@mah-shamim
Comment options

mah-shamim Aug 28, 2024
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants