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.
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.