20. Valid Parentheses 🔍
Difficulty: Easy
- Tags: Stack
, String
Problem Statement 📜
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
, and ']'
, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.
Examples 🌟
🔹 Example 1:
Input:
Output:
🔹 Example 2:
Input:
Output:
🔹 Example 3:
Input:
Output:
Constraints ⚙️
1 <= s.length <= 10^4
s
consists of parentheses only'()[]{}'
.
Solution 💡
The problem can be solved using a stack:
Push opening brackets (
(
,{
,[
) onto the stack.When encountering a closing bracket (
)
,}
,]
):Check if the stack is not empty and if the top of the stack matches the closing bracket. If it matches, pop the stack.
Otherwise, the string is invalid.
At the end, the stack must be empty for the string to be valid.
Java Solution
Explanation of the Solution
Stack Usage:
A stack is used to track unmatched opening brackets.
Opening brackets are pushed onto the stack, and closing brackets attempt to match the top of the stack.
Validation:
If the stack is empty before encountering a closing bracket or the top of the stack doesn't match the closing bracket, the string is invalid.
Final Check:
At the end of the traversal, the stack should be empty for the string to be valid.
Time Complexity ⏳
O(n): Each character is processed once, and stack operations (push/pop) are O(1).
Space Complexity 💾
O(n): In the worst case, all characters could be pushed onto the stack (e.g., all opening brackets).
You can find the full solution here.
Last updated