Tensorum
YouTubeसीखना शुरू करें
LeetCode 1209 · Stack Simulation / String Processing

Remove All Adjacent Duplicates in String II

LeetCode 1209 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Stack of [char, count]; pop at count k.

मध्यमStringStack

मैंने Remove All Adjacent Duplicates in String II (LeetCode 1209) ऐसे हल किया — Stack Simulation / String Processing पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।

नीचे का विवरण अंग्रेज़ी में है।

Intuition

Keep a stack of (character, run length). A matching character extends the top run; when a run reaches k it disappears, which may bring two runs of the same character together on the next push.

Approach

  1. 1

    New character → push with count 1.

  2. 2

    Same as top → increment; at k, pop.

  3. 3

    Rebuild from the stack.

मैंने कैसे हल किया

Run-length stackPythonO(n) time
class Solution:
    def removeDuplicates(self, s: str, k: int) -> str:
        stack =[]
        for char in s:
            if len(stack)==0 or stack[-1]["char"]!=char:
                stack.append({"char":char,"count":1})
            else:
                stack[-1]["count"]+=1
                if stack[-1]["count"]==k:
                    stack.pop()
        
        res =""
        for item in stack:
            res+=item["char"]*item["count"]
        return res

स्टेप-थ्रू लोड हो रहा है…

Remove All Adjacent Duplicates in String II — अक्सर पूछे जाने वाले प्रश्न

Remove All Adjacent Duplicates in String II के पीछे intuition क्या है?

Keep a stack of (character, run length). A matching character extends the top run; when a run reaches k it disappears, which may bring two runs of the same character together on the next push.

Remove All Adjacent Duplicates in String II (LeetCode 1209) कैसे हल करें?

1. New character → push with count 1. 2. Same as top → increment; at k, pop. 3. Rebuild from the stack.

Remove All Adjacent Duplicates in String II की time और space complexity क्या है?

Time: O(n)। Space: O(n)। (Accepted approach: Run-length stack।)

Remove All Adjacent Duplicates in String II में आम गलतियाँ क्या हैं?

Rebuilding with += in a loop is fine here; ''.join is faster for big inputs.