Problem Statement
Use a stack to check if a string with { and } braces is balanced. A balanced string has matching opening and closing braces, 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 braces 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 brace
{, use the push method to add it to the stack.
- For a closing brace
}, 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 braces 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 braces in the stack.
Code Snippet
Dry Run
For the input "{ {} }":
- Push each opening brace and pop matching closing braces:
- Push
{ → 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 braces in the stack.
Conclusion
Using a stack to check balanced braces 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.