Remove All Adjacent Duplicates in String II
LeetCode 1209 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Stack of [char, count]; pop at count k.
আমি 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
New character → push with count 1.
- 2
Same as top → increment; at k, pop.
- 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.