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.