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.