Problem Statement
Use a stack to check if a string of parentheses is balanced. A balanced string has matching opening and closing parentheses, with each pair correctly nested.
Example Usage
Additional Examples:
- Input:
"((())"
- Input:
"()"
- Input:
")("
JavaScript Stack - Using Custom Stack Class
We’ll use the following custom Stack class to check if the parentheses are balanced. This class includes methods like push, pop, peek, isEmpty, size, and clear.
Dry Run
For the input "(()())":
- Push each opening parenthesis and pop matching closing ones:
- Push
( → Stack: [(]
- Push
( → Stack: [(, (]
- Pop
) → Stack: [(]
- Push
( → Stack: [(, (]
- Pop
) → Stack: [(]
- Pop
) → Stack: []
- Check if stack is empty:
- Stack is empty, so the output is
true.
Complexity Analysis
Custom Defined Stack Methods
- Time Complexity: Each
push and pop operation is O(1), making the solution O(n) for n characters in the string.
- Space Complexity: O(n) for storing parentheses in the stack.
Conclusion
Using a stack to check balanced parentheses is an efficient way to leverage the LIFO property. This approach provides a clean solution for verifying balanced strings and showcases the stack’s effectiveness for nested structures.