Workspace Valid Parentheses
0d
DSA Problem Sheet

Balanced Parentheses

Return 1 if the sequence of opening and closing parentheses is balanced, otherwise 0. Encode ( as 1 and ) as -1.

EXECUTION LAB

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 0

Visualizer

Step 1 of 5

Empty structure

Inspect the current state

Read the next bracket with 0 unmatched openings.

Variable watch

i 0top 0stack [0,0,0,0]

Step explanation

Read the next bracket with 0 unmatched openings.

comparisons 1reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(n) time · O(n) explicit teaching stack space

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 1Each opening ticket reserves one return visit. A return without a ticket is invalid.
Hint 2A closing symbol must consume an available opening symbol. All openings must be consumed at the end.
Hint 3Step 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?