Balanced Parentheses Problem Using Stack in DSA Java - 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 the string size increases?
Analyze the time complexity of the following code snippet.
public boolean isBalanced(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else {
if (stack.isEmpty() || !matches(stack.pop(), c)) {
return false;
}
}
}
return stack.isEmpty();
}
private boolean matches(char open, char close) {
return (open == '(' && close == ')') ||
(open == '{' && close == '}') ||
(open == '[' && close == ']');
}
This code checks if the parentheses in the string are balanced using a stack.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character of the string once.
- How many times: Exactly once for each character, so n times where n is string length.
As the string gets longer, the number of steps grows directly with its length.
| 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 in a straight line as input size grows.
Time Complexity: O(n)
This means the time to check balanced parentheses grows linearly with the string length.
[X] Wrong: "The time grows faster because of the stack operations inside the loop."
[OK] Correct: Each character is processed once, and stack operations are simple and fast, so they don't add extra loops or repeated work.
Understanding this linear time check helps you solve many problems involving matching pairs efficiently, a common skill interviewers look for.
"What if the input string contains only opening parentheses? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem goal
The Balanced Parentheses problem checks if all opening brackets like '(' have a matching closing bracket ')' in the correct order.Step 2: Role of stack in checking
A stack helps track opening brackets and ensures each is closed properly in sequence.Final Answer:
Whether every opening bracket has a matching closing bracket in correct order -> Option AQuick Check:
Balanced parentheses = matching pairs [OK]
- Thinking it checks string length
- Ignoring order of brackets
- Checking only for digits or alphabets
Solution
Step 1: Check correct Stack initialization syntax
In Java, to create a stack of Characters, use: Stack<Character> stack = new Stack<>(); which uses diamond operator for type inference.Step 2: Identify errors in other options
Stack stack = new Stack<Character>(); misses generic type on right side; Stack<Character> stack = Stack(); misses 'new' keyword; Stack<Character> stack = new Stack<Character>; misses parentheses after constructor.Final Answer:
Stack<Character> stack = new Stack<>(); -> Option AQuick Check:
Correct Java stack init = Stack<Character> stack = new Stack<>(); [OK]
- Omitting 'new' keyword
- Missing parentheses after constructor
- Incorrect generic type syntax
String s = "({[]})";
System.out.println(isBalanced(s));
public static boolean isBalanced(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else {
if (stack.isEmpty()) return false;
char top = stack.pop();
if ((c == ')' && top != '(') ||
(c == '}' && top != '{') ||
(c == ']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty();
}Solution
Step 1: Trace the input string "({[]})" character by character
Push '(' '{' '[' onto stack; then pop matching pairs for ']' '}' ')'. Stack ends empty.Step 2: Check final stack state
Stack is empty after processing all characters, so return true.Final Answer:
true -> Option CQuick Check:
All brackets matched = true [OK]
- Not checking stack empty at end
- Mismatching brackets order
- Ignoring empty stack before pop
public static boolean checkBalanced(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else {
char top = stack.pop();
if ((c == ')' && top != '(') ||
(c == '}' && top != '{') ||
(c == ']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty();
}Solution
Step 1: Analyze stack pop operation
Pop is called without checking if stack is empty, which can cause runtime exception if closing bracket appears first.Step 2: Identify missing empty check
Must check stack.isEmpty() before pop to avoid EmptyStackException.Final Answer:
Missing check if stack is empty before pop -> Option DQuick Check:
Always check stack empty before pop [OK]
- Ignoring empty stack before pop
- Assuming input always starts with opening bracket
- Not handling runtime exceptions
"[{()}]({[]})", which of the following modifications to the balanced parentheses algorithm will correctly handle this input and return true?Solution
Step 1: Understand input complexity
The string contains multiple types of brackets nested and sequentially combined.Step 2: Apply stack-based matching for all bracket types
Push opening brackets, pop and match closing brackets; ensure stack empty at end for balanced check.Step 3: Evaluate other options
Length check or ignoring bracket types will fail; two stacks unnecessary and incorrect.Final Answer:
Use a stack and check matching pairs for all bracket types, ensuring stack is empty at end -> Option BQuick Check:
Stack matching all brackets = true [OK]
- Ignoring some bracket types
- Relying on string length only
- Using multiple stacks unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
