Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 402 · Monotonic Stack – Greedy Removal

Remove K Digits

LeetCode 402 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Monotonic increasing stack; pop larger previous digits while k > 0.

நடுத்தரம்StringStackGreedyMonotonic Stack
LeetCode இல் திற ↗

நான் Remove K Digits (LeetCode 402) ஐ இப்படித் தீர்த்தேன் — Monotonic Stack – Greedy Removal பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Earlier digits matter more. Whenever a digit is smaller than the one before it, deleting the bigger previous digit makes the number smaller — so keep an increasing stack and pop while you can still delete.

Approach

  1. 1

    For each digit, pop bigger digits from the stack while k remains.

  2. 2

    Push the digit.

  3. 3

    If deletions remain, cut them from the end.

  4. 4

    Strip leading zeros; empty → '0'.

நான் எப்படித் தீர்த்தேன்

Monotonic stack (greedy)PythonO(n) time
class Solution:
    def removeKdigits(self, num: str, k: int) -> str:
        """
        425
        if we remove leftmost 4 we will get 25
        if keep it then we may get 42,45
        1 condition - since 4>2 remove 4 

        monotonic increasing seq - 123
        #remove 3 
        #we will 12
        #if keep 3, we may get 13,23 which is not minimum
        """
        stack = []
        for digit in num:
            #425
            while k and stack and digit< stack[-1]:
                k-=1
                stack.pop()
            stack.append(digit)
        #123
        final_stack = stack[:-k] if k>0 else stack
        return "".join(final_stack).lstrip("0") or "0" #0123 - min num is 0 
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Remove K Digits — அடிக்கடி கேட்கப்படும் கேள்விகள்

Remove K Digits பின்னாலுள்ள intuition என்ன?

Earlier digits matter more. Whenever a digit is smaller than the one before it, deleting the bigger previous digit makes the number smaller — so keep an increasing stack and pop while you can still delete.

Remove K Digits (LeetCode 402) ஐ எப்படித் தீர்ப்பது?

1. For each digit, pop bigger digits from the stack while k remains. 2. Push the digit. 3. If deletions remain, cut them from the end. 4. Strip leading zeros; empty → '0'.

Remove K Digits இன் time மற்றும் space complexity என்ன?

Time: O(n). Space: O(n). (Accepted approach: Monotonic stack (greedy).)

Remove K Digits இல் பொதுவான தவறுகள் என்ன?

Leftover k comes off the end (the stack is increasing there). Don't return an empty string.