I could not solve it when I saw this problem 1st time, I am proud that today I cracked this problem before watching your video. Thanks for posting videos, your content definitely helps me to progress!
Sometimes it’s like that. I can’t tell you how many solutions I had to look at and videos to watch before things started clicking for me. I think as long as you understand how/why a solution works, there’s no problem looking at it if you are stuck. It’s just important to learn it so that when you inevitably come across another similar question, you can apply what you learned
Why can’t you have a stack : push when you see ‘(‘ pop when you see’)’ if there is nothing to pop then the remaining ‘)’ are to be removed. Store the indices of ‘)’ and return the string without them. Any thing wrong with this approach?
Cleaner and more intuitive approch class Solution(object): def minRemoveToMakeValid(self, s): stack = [] s = list(s) # Iterate through the string and handle parentheses for i, c in enumerate(s): if c == "(": stack.append((i, "(")) elif c == ")": if stack and stack[-1][1] == "(": stack.pop() # Valid pair else: stack.append((i, ")")) # Unmatched closing parenthesis # Update unwanted parentheses with '-1' while stack: index, _ = stack.pop() s[index] = '' # Rebuild the final valid string return "".join(s)
I feel the last several lines "elif cur_char == ")" res.append(cur_char)else:res.append(cur_char)" can be simply combined to "else:res.append(cur_char)"