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.
Approach
- Initialize a Stack: Create an instance of the
Stack class.
- Push and Pop Operations:
- Traverse each character in the string.
- For an opening parenthesis
(, use the push method to add it to the stack.
- For a closing parenthesis
), use the pop method to remove the top element from the stack.
- If a
pop is attempted on an empty stack or the final stack isn’t empty, the string is unbalanced.
- Return Result: If the stack is empty at the end, the parentheses are balanced.
Steps
- Create an instance of the
Stack class.
- Loop through each character in the input string.
- Use
push for ( and pop for ).
- Check if the stack is empty at the end to determine if the string is balanced.
Time & Space Complexity
- Time Complexity:
push and pop operations are O(1), and each character in the string is processed once, so the overall complexity is O(n), where n is the length of the string.
- Space Complexity: O(n), as we may need to store up to
n parentheses in the stack.
Code Snippet
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.