Given a string of brackets, find an index where the number of opening brackets is equal to the number of closing brackets.
Create two lists: open_list and close_list, both of size input_length + 1 and filled with zeros. These lists will help track the count of open and closing brackets.
If the last element in open_list is 0, it means there are no unmatched opening brackets. Return the length of the input string. If the first element in close_list is 0, it means there are no unmatched closing brackets. Return 0. Otherwise, iterate through both lists. If the value at the same index in both lists is equal, it means that up to that index, the number of opening and closing brackets matches. Return the index.
s = "(()))(()()())))" l = len(s) opn = [0] * (l + 1) cls = [0] * (l + 1) idx = -1 for i in range(l): if s[i] == '(': opn[i + 1] = opn[i] + 1; else: opn[i + 1] = opn[i]; for i in range(l - 1, -1, -1): if s[i] == ')': cls[i] = cls[i + 1] + 1 else: cls[i] = cls[i + 1] if opn[l] == 0: print(l) if cls[0] == 0: print(0) i = 0 while i <= l: if opn[i] == cls[i]: idx = i i += 1 print(idx)
const str = "(()))(()()())))"; const len = str.length; const opn = Array(len + 1).fill(0); const cls = Array(len + 1).fill(0); let idx = -1; for (let i = 0; i < len; i++) { if (str[i] == '(') { opn[i + 1] = opn[i] + 1; } else { opn[i + 1] = opn[i]; } } for (let i = len - 1; i >= 0; i--) { if (str[i] == ')') { cls[i] = cls[i + 1] + 1; } else { cls[i] = cls[i + 1]; } } if (opn[len] == 0) { console.log(len); } if (cls[0] == 0) { console.log(0); } for (let i = 0; i <= len; i++) { if (opn[i] == cls[i]) { idx = i; } } console.log(idx);