Valid Parentheses in Python and Java
In this tutorial, we will learn LeetCode #20: Valid Parentheses in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the Valid Parentheses Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use stack because it gives a clean and optimized solution.
Example input:
s = "({[]})"
Expected result:
Output: true
Explanation:
Every opening bracket is closed correctly.Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example:
s = "({[]})"
Approach:
stack
We update variables step by step until we reach:
Output: trueWhy Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why stack is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1
Use this input.
s = "({[]})"
stack = []
Step 2
First character is (. It is an opening bracket.
stack = ["("]
Step 3
Next character is {. It is also opening.
stack = ["(", "{"]
Step 4
Next character is [.
stack = ["(", "{", "["]
Step 5
Next character is ]. It matches [.
Pop [ from stack.
stack = ["(", "{"]
Step 6
After matching all closing brackets, stack becomes empty.
Final answer = trueImportant Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: true
Example 1
Input:
s = "({[]})"
Output:
Output: true
Explanation:
Every opening bracket is closed correctly.Example 2
Input:
s = "{[()]}"
Output:
true
Explanation:
Every opening bracket has the correct closing bracket.Python Code
Here is the complete Python solution for LeetCode #20.
class ParenthesesValidator:
def is_valid(self, s):
stack = []
pairs = {")": "(", "]": "[", "}": "{"}
for char in s:
if char in pairs.values():
stack.append(char)
else:
if not stack or stack.pop() != pairs[char]:
return False
return len(stack) == 0
validator = ParenthesesValidator()
print(validator.is_valid("{[()]}") ) # Output: True
print(validator.is_valid("{[(])}")) # Output: FalseJava Code
Here is the complete Java solution for LeetCode #20.
import java.util.Stack;
class ParenthesesValidator {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char ch : s.toCharArray()) {
if (ch == '(' || ch == '[' || ch == '{') {
stack.push(ch);
} else {
if (stack.isEmpty()) {
return false;
}
char top = stack.pop();
if ((ch == ')' && top != '(') || (ch == ']' && top != '[') || (ch == '}' && top != '{')) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
ParenthesesValidator validator = new ParenthesesValidator();
System.out.println(validator.isValid("{[()]}") ); // Output: true
System.out.println(validator.isValid("{[(])}")); // Output: false
}
}Time and Space Complexity
Time Complexity: O(n)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(n)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #20: Valid Parentheses becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.