š Scenario: Imagine you are building a simple code editor that checks if the parentheses in a line of code are balanced. Balanced parentheses mean every opening bracket has a matching closing bracket in the correct order.
šÆ Goal: You will create a program that uses a stack to check if a given string of parentheses is balanced or not.
š What You'll Learn
Create a string variable with a specific parentheses sequence
Create an empty stack using an array
Use a loop to check each character and update the stack accordingly
Print Balanced if parentheses are balanced, otherwise print Not Balanced
š” Why This Matters
š Real World
Checking balanced parentheses is important in code editors, compilers, and calculators to ensure expressions are correct.
š¼ Career
Understanding stacks and balanced parentheses is a common interview question and a fundamental concept in programming and software development.
Progress0 / 4 steps
1
Create the parentheses string
Create a string variable called parentheses and set it to the exact value '(()())'.
DSA Typescript
Hint
Use const to create a string variable with the given parentheses.
2
Create an empty stack
Create an empty array called stack to use as a stack.
DSA Typescript
Hint
Use const stack: string[] = []; to create an empty array for the stack.
3
Check parentheses using a loop and stack
Use a for loop with variable char to iterate over each character in parentheses. Inside the loop, if char is '(', push it to stack. If char is ')', pop from stack. If stack is empty when popping, set a boolean variable isBalanced to false and break the loop. Initialize isBalanced as true before the loop. After the loop, if stack is not empty, set isBalanced to false.
DSA Typescript
Hint
Use a for...of loop to check each character. Use stack.push() and stack.pop() to manage the stack. Use isBalanced to track if parentheses are balanced.
4
Print the result
Print 'Balanced' if isBalanced is true, otherwise print 'Not Balanced'.
DSA Typescript
Hint
Use console.log() to print the result based on isBalanced.
Practice
(1/5)
1. What is the core idea behind using a stack to validate balanced parentheses?
easy
A. Count total opening and closing brackets and compare
B. Push opening brackets onto the stack; when a closing bracket appears, check if the top matches
C. Sort the string and compare first and last characters
D. Use a counter that increments for '(' and decrements for ')'
Solution
Step 1: Stack tracks unmatched opens
Opening brackets are pushed onto the stack. Each closing bracket must match the most recent unmatched opening bracket - the stack top.
Step 2: Why stack, not counter
A counter works for a single bracket type but fails for mixed types: '([)]' has equal counts but is invalid. Stack tracks TYPE and ORDER.
Final Answer:
Push open, match against stack top on close. -> Option B
Quick Check:
Stack: push '(' '[' '{'. On close, pop and verify match. [OK]
Hint: Stack: push opens, pop+match on close. Counter alone fails for mixed bracket types. [OK]
Common Mistakes:
Using a counter which fails for '([)]'
Not checking bracket TYPE when matching
Forgetting to check stack is empty at the end
2. What should be returned when a closing bracket is encountered but the stack is empty?
easy
A. true - the string might still be balanced
B. false - there is no matching opening bracket
C. Push the closing bracket and continue
D. Skip it and continue scanning
Solution
Step 1: Empty stack on close
If we see ')' but the stack is empty, there is no unmatched opening bracket to pair with it. The string is invalid.
Step 2: Return false immediately
No need to continue scanning - return false right away.
Final Answer:
Return false - unmatched closing bracket. -> Option B
Quick Check:
Close on empty stack = unmatched = false. [OK]
Hint: Empty stack + closing bracket = instant false. No match possible. [OK]
Common Mistakes:
Continuing to scan (wastes time, wrong)
Pushing closing bracket (corrupts the stack)
Returning true (incorrect)
3. Is '([)]' a valid balanced parentheses string?
medium
A. Yes - it has equal counts of each bracket type
B. No - the brackets are nested incorrectly
C. Yes - all brackets are closed
D. Yes - opening and closing counts match
Solution
Step 1: Trace the stack
Push '(': stack=['(']. Push '[': stack=['(','[']. See ')': stack top is '[' ā ')' - MISMATCH. Return false.
Step 2: Why counting fails
Count approach: 1 '(', 1 '[', 1 ')', 1 ']' - all equal. But stack reveals the TYPE mismatch.
Final Answer:
Invalid - '[' is at top when ')' arrives. -> Option B
4. What is the time and space complexity of the stack-based balanced parentheses solution?
medium
A. Time O(n²), Space O(1)
B. Time O(n log n), Space O(n)
C. Time O(n), Space O(n)
D. Time O(n), Space O(1)
Solution
Step 1: Time
Single pass through string: O(n). Each character: one push or one pop - O(1) each. Total: O(n).
Step 2: Space
Stack can hold up to n/2 characters in worst case '((((...)))'. Space: O(n).
Final Answer:
Time O(n), Space O(n). -> Option C
Quick Check:
One pass = O(n). Stack = O(n) worst case. [OK]
Hint: Balanced parentheses: O(n) time (one pass), O(n) space (stack). [OK]
Common Mistakes:
Saying O(1) space - stack can grow to O(n)
Saying O(n²) - only one pass needed
Confusing with sorting-based approaches
5. Which TypeScript code correctly implements the balanced parentheses check?
hard
A. return s.split('').filter(c => '({['.includes(c)).length === s.split('').filter(c => ')}]'.includes(c)).length;
B. const stack: string[] = []; const map: Record = {')':'(', ']':'[', '}':'{'}; for (const c of s) { if ('([{'.includes(c)) stack.push(c); else if (stack.pop() !== map[c]) return false; } return stack.length === 0;
C. let count = 0; for (const c of s) { if (c === '(') count++; else count--; if (count < 0) return false; } return count === 0;
D. return s.length % 2 === 0;
Solution
Step 1: Map for bracket pairs
map pairs each closing bracket to its expected opening. On close: pop stack and check it matches map[c].
Step 2: Final check
stack.length === 0 ensures no unmatched opening brackets remain.
Why A fails
Only counts, doesn't check types or order.
Why C fails
Counter only works for '()' - fails for '([)]' or mixed types.
Final Answer:
Option B - map + stack with type checking. -> Option B
Quick Check:
Map + stack + empty check at end = correct solution. [OK]
Hint: Use map {')':'(', ']':'[', '}':'{'} + stack. Pop on close, check match. Return stack.length===0. [OK]
Common Mistakes:
Using count only (fails mixed brackets)
Not checking stack empty at end (unmatched opens)
Not using a map for bracket pairs
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.