Balanced Brackets

  • + 1 comment

    My Python code works for most of the test cases, but is unable to finish within the time limits for some of the test cases. Can anyone help me optimize my code? It starts off by making sure that there is an even number of brackets. Next, if a pair of brackets are next to each other, they get removed. This is continued until there is nothing left, meaning that those brackets are balanced, or until nothing happens, meaning that those brackets are not balanced.

        s = list(s)
        old = []
        front = ["(", "[", "{"]
        back = [")", "]", "}"]
        if len(s) % 2 == 1:
            return "NO"
        while len(s) != 0:
            old = copy.deepcopy(s)
            for a in range(len(s) - 1):
                if s[a] in front and s[a + 1] in back:
                    if front.index(s[a]) == back.index(s[a + 1]):
                        s.pop(a)
                        s.pop(a)
                        break
            if old == s:
                return "NO"
        return "YES"