Continue learning
Practice related DSA questions in the same topic.
Return 1 if the sequence of opening and closing parentheses is balanced, otherwise 0. Encode ( as 1 and ) as -1.
Return 1 if the sequence of opening and closing parentheses is balanced, otherwise 0. Encode ( as 1 and ) as -1.
def solve(values, target): stack = [0] * (len(values)) top = 0 i = 0 while (i < len(values)): if (values[i] == 1): stack[top] = i top = (top + 1) else: if (top == 0): return 0 top = (top - 1) i = (i + 1) if (top == 0): return 1 return 0Empty structure
Read the next bracket with 0 unmatched openings.
Read the next bracket with 0 unmatched openings.
Each opening ticket reserves one return visit. A return without a ticket is invalid.
A closing symbol must consume an available opening symbol. All openings must be consumed at the end.
O(n) time · O(n) explicit teaching stack auxiliary space
Worked example · {"values":[1,1,-1,-1],"target":0} ⇒ 1
Edge case 1 · {"values":[-1,1],"target":0} ⇒ 0
Edge case 2 · {"values":[],"target":0} ⇒ 1
Edge case 3 · {"values":[1],"target":0} ⇒ 0
A final balance of zero alone cannot rule out an invalid closing prefix.
How would several types of bracket change your state?