Remove K Digits

MediumStackmonotonic stack

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a string num representing a non-negative integer and an integer k. Delete exactly k digits from num (the remaining digits keep their relative order) so that the resulting number is as small as possible. Return the result as a string **without leading zeros**. If every digit is removed, or only zeros remain, return "0". Aim for O(n) time.

Examples

Input: num = "1432219", k = 3
Output: "1219"
Removing 4, 3, and the first 2 leaves 1219.
Input: num = "10200", k = 1
Output: "200"
Removing the leading 1 leaves "0200", which is written as "200".
Input: num = "10", k = 2
Output: "0"
Nothing remains, so the answer is "0".

Constraints

  • 0 <= k <= num.length <= 10^5
  • num consists of digits only
  • num has no leading zeros except the number zero itself

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More monotonic stack problems