0

I am solving the following Leetcode problem: https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/

Here is my coded solution:

def minRemoveToMakeValid(s: str) -> str:
    count = 0
    pointer = 0
    while pointer < len(s):  # points to the last char of s
        if count >= 0:
            if s[pointer] == "(":
                count += 1
            elif s[pointer] == ")":
                count -= 1
            pointer += 1
            print(pointer)

        else:
            if s[pointer] == ")":
                s = s.replace(s[pointer], " ", 1)
                count += 1
                pointer +=1

    if count > 0:
        s = s[::-1]
        s.replace("(", "", count)
        s = s[::-1]
    s = s.replace(" ", "")

    return s

print(minRemoveToMakeValid("a)b(c)d"))

For some reason the while loop is stuck on 2 (as suggested by the print statement)- any ideas why this is? I suspect it is because I am replacing ")", but in my mind I've accounted for this.

  • there are several if statements. You update pointer += 1 in "most" of them ... perhaps look at the value when it gets stuck in an infinite loop. – Kenny Ostrom Jun 18 '21 at 13:30
  • 1
    If `count` is negative, and `s[pointer]` is anything other than ")", the body of the `while` loop does nothing - you're in an infinite loop. – jasonharper Jun 18 '21 at 13:34
  • With a decent debugger you can analyse this yourself: set breakpoints, inspect variables, step through the code, and the *"for some reason..."* will be clarified. Unless of course, your prefer not to debug, and rely on the community to be your debugger tool? – trincot Jun 18 '21 at 13:47
  • [How to step through Python code to help debug issues?](https://stackoverflow.com/a/4929267/15740324) – Standard_101 Jun 18 '21 at 14:28
  • Thanks Jason- is there a way I could have figured this out ? I use Pycharm and tried to use their debugger but it doesn't really indicate that this is the issue, but by using print() statements I could see that it is stuck at iteration 2/3 – Patrick Chong Jun 19 '21 at 09:30

0 Answers0