Balanced Parentheses Problem Using Stack in DSA Javascript - Time & Space Complexity
We want to know how the time needed to check balanced parentheses grows as the input string gets longer.
How does the number of steps change when we have more characters to check?
Analyze the time complexity of the following code snippet.
function isBalanced(s) {
const stack = [];
for (const char of s) {
if (char === '(') {
stack.push(char);
} else if (char === ')') {
if (stack.length === 0) return false;
stack.pop();
}
}
return stack.length === 0;
}
This code checks if parentheses in a string are balanced using a stack.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character in the string once.
- How many times: Exactly once for each character in the input string.
As the input string gets longer, the number of steps grows directly with the number of characters.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and stack operations |
| 100 | About 100 checks and stack operations |
| 1000 | About 1000 checks and stack operations |
Pattern observation: The steps increase evenly as the input size increases.
Time Complexity: O(n)
This means the time to check balanced parentheses grows in a straight line with the input size.
[X] Wrong: "The time grows faster because of the stack operations inside the loop."
[OK] Correct: Each stack operation (push/pop) takes constant time, so they don't add extra loops or slow down the process beyond the single pass.
Understanding this helps you explain how simple data structures like stacks can efficiently solve common problems, a skill valued in many coding challenges.
"What if we had to check for multiple types of brackets like (), {}, and []? How would the time complexity change?"
Practice
Balanced Parentheses Problem?Solution
Step 1: Understand the role of stack in matching parentheses
A stack helps store opening parentheses as they appear, so we can check if each closing parenthesis matches the last opened one.Step 2: Explain why other options are incorrect
Counting or reversing parentheses does not help check if they are balanced. Sorting changes order and breaks the original sequence.Final Answer:
To keep track of opening parentheses and match them with closing ones -> Option DQuick Check:
Stack tracks openings for matching [OK]
- Thinking stack counts parentheses instead of matching
- Assuming reversing string solves balance
- Confusing sorting with balancing
Solution
Step 1: Recall JavaScript array method for adding elements at the end
JavaScript arrays usepush()to add elements to the end, which simulates stack push.Step 2: Identify incorrect methods
add(),insert(), andappend()are not valid JavaScript array methods.Final Answer:
stack.push(element); -> Option BQuick Check:
Use push() to add to stack [OK]
- Using add() or append() which are not JavaScript array methods
- Confusing push() with pop()
- Trying to use insert() which doesn't exist
function isBalanced(s) {
const stack = [];
for (const char of s) {
if (char === '(') stack.push(char);
else if (char === ')') {
if (stack.length === 0) return false;
stack.pop();
}
}
return stack.length === 0;
}
console.log(isBalanced('(()())'));
console.log(isBalanced('(()'));
console.log(isBalanced(')('));Solution
Step 1: Trace the function for each input string
For '(()())': all parentheses match, stack ends empty, returns true.
For '(()': one '(' remains unmatched, returns false.
For ')(': first char is ')', stack empty, returns false.Step 2: Confirm outputs match true, false, false
Outputs are true, false, false respectively.Final Answer:
true, false, false -> Option CQuick Check:
Stack empty at end means balanced [OK]
- Assuming unmatched openings are balanced
- Ignoring early unmatched closing parentheses
- Confusing true/false outputs
function checkBalance(str) {
const stack = [];
for (let i = 0; i < str.length; i++) {
if (str[i] === '(') {
stack.push('(');
} else {
if (stack.length === 0) return false;
stack.pop();
}
}
return true;
}Solution
Step 1: Analyze the return statement after loop
The function returns true without checking if stack is empty, so leftover '(' are ignored.Step 2: Explain why this causes incorrect results
If there are unmatched '(' left in stack, string is unbalanced but function returns true incorrectly.Final Answer:
It returns true even if stack is not empty after loop -> Option AQuick Check:
Check stack.length === 0 before return true [OK]
- Forgetting to check stack length after loop
- Returning true too early
- Ignoring unmatched opening parentheses
s = '{[()]}', which modification is needed in the stack-based balanced parentheses algorithm to correctly check this string?Solution
Step 1: Understand the input string contains multiple bracket types
The string has '()', '{}', and '[]' brackets, so the algorithm must handle all types.Step 2: Explain how to handle multiple bracket types with one stack
Push opening brackets onto stack, and on closing bracket, check if it matches the last opening bracket type before popping.Final Answer:
Add support for matching pairs of '()', '{}', and '[]' with stack push/pop logic -> Option AQuick Check:
One stack handles all bracket types [OK]
- Ignoring bracket types other than parentheses
- Using multiple stacks unnecessarily
- Reversing string instead of matching pairs
Ready to prove it?
Pass the test and this pattern moves unknown
