🧠
Optimized Stack Approach (Using Array as Stack and Early Exit)
💡 This approach optimizes the stack implementation by using an array and exits early when invalidity is detected, improving runtime slightly.
Intuition
Use an array as a stack for better performance. As soon as a mismatch is found, return false immediately to avoid unnecessary processing.
Algorithm
- Initialize an empty array to simulate a stack.
- Iterate over each character in the string.
- If it is an opening bracket, push it onto the array.
- If it is a closing bracket, check if the last element matches; if not, return false immediately.
- Pop the last element if matched.
- Return true if the array is empty after processing.
💡 Early exit reduces unnecessary checks, which is important in large inputs.
def isValid(s: str) -> bool:
stack = []
pairs = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in pairs.values():
stack.append(char)
elif char in pairs:
if not stack or stack[-1] != pairs[char]:
return False
stack.pop()
else:
return False
return not stack
# Driver code
if __name__ == '__main__':
test_cases = ["()[]{}", "(]", "", "((", ")"]
for tc in test_cases:
print(f"Input: {tc} -> Output: {isValid(tc)}")
Line Notes
stack = []Use list as stack for efficient append/pop
pairs = {')': '(', ']': '[', '}': '{'}Dictionary for quick matching
if not stack or stack[-1] != pairs[char]Early exit if mismatch or empty stack
return not stackTrue if all matched and stack empty
import java.util.*;
public class ValidParentheses {
public static boolean isValid(String s) {
char[] stack = new char[s.length()];
int top = -1;
Map<Character, Character> pairs = Map.of(')', '(', '}', '{', ']', '[');
for (char c : s.toCharArray()) {
if (pairs.containsValue(c)) {
stack[++top] = c;
} else if (pairs.containsKey(c)) {
if (top == -1 || stack[top] != pairs.get(c)) {
return false;
}
top--;
} else {
return false;
}
}
return top == -1;
}
public static void main(String[] args) {
String[] testCases = {"()[]{}", "(]", "", "((", ")"};
for (String tc : testCases) {
System.out.println("Input: " + tc + " -> Output: " + isValid(tc));
}
}
}
Line Notes
char[] stack = new char[s.length()];Use array as stack for performance
int top = -1;Track top index of stack
if (top == -1 || stack[top] != pairs.get(c))Early exit on mismatch or empty stack
return top == -1;True if stack empty after processing
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
bool isValid(string s) {
char *stack = new char[s.length()];
int top = -1;
unordered_map<char, char> pairs = {{')', '('}, {'}', '{'}, {']', '['}};
for (char c : s) {
if (c == '(' || c == '{' || c == '[') {
stack[++top] = c;
} else {
if (top == -1 || stack[top] != pairs[c]) {
delete[] stack;
return false;
}
top--;
}
}
bool result = (top == -1);
delete[] stack;
return result;
}
int main() {
string testCases[] = {"()[]{}", "(]", "", "((", ")"};
for (auto &tc : testCases) {
cout << "Input: " << tc << " -> Output: " << (isValid(tc) ? "true" : "false") << endl;
}
return 0;
}
Line Notes
char *stack = new char[s.length()];Use dynamic array as stack for speed
int top = -1;Top index of stack
if (top == -1 || stack[top] != pairs[c])Early return on mismatch or empty stack
delete[] stack;Free allocated memory to avoid leaks
function isValid(s) {
const stack = [];
const pairs = {')': '(', '}': '{', ']': '['};
for (const char of s) {
if (Object.values(pairs).includes(char)) {
stack.push(char);
} else if (pairs[char]) {
if (stack.length === 0 || stack[stack.length - 1] !== pairs[char]) {
return false;
}
stack.pop();
} else {
return false;
}
}
return stack.length === 0;
}
// Test cases
const testCases = ["()[]{}", "(]", "", "((", ")"];
testCases.forEach(tc => console.log(`Input: ${tc} -> Output: ${isValid(tc)}`));
Line Notes
const stack = [];Array used as stack for efficient push/pop
const pairs = {')': '(', '}': '{', ']': '['};Mapping for quick bracket matching
if (stack.length === 0 || stack[stack.length - 1] !== pairs[char])Early exit on mismatch or empty stack
return stack.length === 0;True if all brackets matched and stack empty
Processes each character once with O(1) stack operations and early exits on mismatch.
💡 For large n, early exit can save significant time compared to always processing entire string.
Interview Verdict: Accepted / Slightly optimized stack solution
This is a practical optimization of the standard stack approach, useful in interviews to show attention to detail.