Balanced Parentheses
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.
Input and constraints
- Use 1 for an opening parenthesis and -1 for a closing parenthesis.
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
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 0Visualizer
Step 1 of 5Empty structure
Inspect the current state
Read the next bracket with 0 unmatched openings.
Variable watch
Step explanation
Read the next bracket with 0 unmatched openings.
Worked explanation
Each opening ticket reserves one return visit. A return without a ticket is invalid.
Guided solution
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
Examples
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
Progressive hints
Hint 1
Each opening ticket reserves one return visit. A return without a ticket is invalid.Hint 2
A closing symbol must consume an available opening symbol. All openings must be consumed at the end.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
A final balance of zero alone cannot rule out an invalid closing prefix.
Interview follow-up
How would several types of bracket change your state?