Valid Parentheses β Complete LeetCode Solution with Stack Pattern
Let BliniBot prep you for interviews
Try BliniBot FreeThe Valid Parentheses problem is one of the most frequently tested coding interview questions and a perfect example of the Stack pattern. Understanding this problem deeply will help you recognize and solve dozens of related problems that share the same underlying algorithmic structure. In this guide, we provide a complete walkthrough of the solution in both Python and TypeScript, explain the time and space complexity, discuss common variations, and show you how to recognize when to apply the Stack pattern in new problems. Whether you are preparing for interviews at Google, Amazon, Meta, or any top tech company, mastering this fundamental pattern is essential. We start with the brute force approach to build intuition, then optimize step by step to arrive at the optimal solution. Each step is explained with the reasoning behind it so you can reproduce this thinking process in an actual interview rather than relying on memorization. The Stack pattern appears in approximately 15 to 20 percent of all coding interview questions, making it one of the highest-leverage patterns to study thoroughly.
Problem Statement and Examples
Use a stack to track opening brackets. When encountering a closing bracket, check if the top of the stack matches. If the stack is empty at the end, the string is valid. This problem is classified as Easy difficulty, though the Stack technique it requires appears in problems across all difficulty levels. Understanding the core mechanic here unlocks solutions to many harder problems. Let us first examine what makes this problem well-suited for this approach: we need to process elements in a way that avoids redundant computation, and the pattern gives us exactly that efficiency. The brute force approach would check all possible combinations, resulting in O(n squared) or worse time complexity. The Stack optimization reduces this dramatically by maintaining state intelligently as we traverse the input. Before coding, always verify your understanding by working through small examples by hand β this catches misunderstandings early and demonstrates thoroughness to your interviewer.
Python Solution
Here is the optimal Python solution using the Stack pattern. Python's clean syntax makes the algorithm's logic easy to follow. Pay attention to how we initialize our data structures and handle edge cases before entering the main loop. The variable naming reflects the algorithmic concept to make the code self-documenting. In an interview, writing clean and readable code like this signals professionalism and attention to detail. Let us walk through the code line by line and understand why each decision was made.
def is_valid(s):
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping:
if not stack or stack[-1] != mapping[char]:
return False
stack.pop()
else:
stack.append(char)
return len(stack) == 0TypeScript Solution
The TypeScript implementation uses the same algorithmic approach with proper type annotations. TypeScript's type system helps catch errors at compile time and makes the code more maintainable. Notice how the generic types and interfaces document the expected input and output formats. If your target company uses TypeScript (which is increasingly common in 2026), demonstrating fluency in typed solutions gives you an edge. The logic mirrors the Python solution exactly, so understanding one helps you write the other quickly.
function isValid(s: string): boolean {
const stack: string[] = [];
const map: Record<string, string> = {')':'(', '}':'{', ']':'['};
for (const c of s) {
if (c in map) {
if (!stack.length || stack[stack.length-1] !== map[c]) return false;
stack.pop();
} else stack.push(c);
}
return stack.length === 0;
}Have a question about Valid Parentheses β Complete LeetCode Solution with Stack Pattern?
Ask BliniBot βComplexity Analysis
Time complexity: O(n). Space complexity: O(n). Understanding complexity analysis is critical because interviewers almost always ask about it, and incorrect analysis can cost you the problem even if your code is correct. For time complexity, count how many times each element is processed β in the Stack pattern, each element is typically visited a constant number of times, giving us linear time. For space complexity, consider the auxiliary data structures used beyond the input and output. In this solution, the space usage is O(n) because we store at most n elements in our auxiliary data structure. When comparing approaches, an algorithm that is O(n) time and O(n) space is generally preferred over O(n log n) the and O(1) the for most interview contexts, since the complexity is usually the primary optimization target.
Ready to automate? BliniBot connects to 200+ tools.
Start Free TrialWhen to Use the Stack Pattern
The Stack pattern is applicable when you see these characteristics in a problem: the input involves a linear data structure (array, string, or linked list), you need to find or optimize something among contiguous or related elements, and a brute force approach would involve nested loops. Common signal words include "subarray," "substring," "consecutive," "contiguous," "minimum/maximum window," and "pair." Practice recognizing these signals across different problem phrasings. The Stack pattern also combines well with other techniques: you might use Stack as the outer strategy and binary search or hash maps as inner tools. Building this pattern recognition through deliberate practice is more effective than solving hundreds of random problems. Focus on understanding why the pattern works, not just how to apply it mechanically.
- Look for problems involving contiguous elements or subsequences in arrays and strings
- Check if brute force would require nested iteration that the Stack can eliminate
- Consider whether maintaining running state eliminates recomputation
- Practice converting brute force to Stack solutions to build intuition for the optimization step
Common Variations and Follow-ups
Interviewers frequently modify this problem to test deeper understanding. Common variations include: changing the constraint (find all pairs vs first pair, minimum vs maximum), modifying the input format (sorted vs unsorted, with duplicates vs without), adding constraints (in-place modification, space limit), or extending to higher dimensions (2D matrix version). For each variation, the core Stack technique remains but the implementation details change. Practice at least 3 to 4 variations of every core problem to build the flexibility needed for interview success. When you encounter a variation in an interview, explicitly state how it differs from the base problem and how that difference affects your approach β this demonstrates depth of understanding that impresses interviewers. The Valid Parentheses problem also frequently appears as a subproblem within harder questions, so understanding it thoroughly provides building blocks for tackling complex problems.
Key Takeaways
- 1.The Valid Parentheses problem is best solved using the Stack pattern with O(n) time complexity
- 2.Always start with brute force to build intuition before optimizing to the Stack approach
- 3.Practice recognizing signal words that indicate when the Stack pattern applies
- 4.Master both Python and TypeScript implementations since companies test in different languages
- 5.Understand complexity analysis deeply β interviewers expect you to justify your Big-O claims
Frequently Asked Questions
What is the optimal time complexity for Valid Parentheses?
The optimal solution runs in O(n) time and O(n) space. The Stack technique achieves this by processing each element a constant number of times, avoiding the nested iteration that a brute force approach would require. Any solution faster than this would need to skip elements, which risks missing the correct answer for this problem. In an interview, state the complexity clearly and be prepared to prove it by tracing through the algorithm with a sample input.
How do I recognize Stack problems in interviews?
Look for these patterns: the problem involves a linear data structure, you need to find an optimal substructure or pair, and brute force would require quadratic time. Signal words include contiguous, subarray, substring, pair, window, and consecutive. The Stack pattern is one of the most versatile techniques, appearing in approximately 15 to 20 percent of coding interviews. Practice identifying these signals in problem statements before reading the solution to build your pattern recognition ability.
Should I memorize the solution to Valid Parentheses?
No. Memorization fails in interviews because interviewers modify problems to test understanding, not recall. Instead, understand why the Stack approach works for this problem structure. Learn the pattern, practice applying it to multiple problems, and build the ability to derive solutions from first principles. If you understand the underlying mechanics, you can handle any variation the interviewer throws at you, which is exactly what they are testing.
What if I get stuck on Valid Parentheses during an interview?
Start with the brute force approach and explain it clearly. Then analyze what makes it slow (usually redundant computation in nested loops). Ask yourself: what information from the previous iteration can I reuse? This naturally leads to the Stack optimization. Communicate your thought process throughout β interviewers give credit for systematic problem-solving even if you do not reach the optimal solution immediately. Asking good clarifying questions and testing with examples also buys thinking time.
Related Articles
Research companies and their tech stacks before your next interview. Analyze top companies β
NexusBro helps developers catch bugs and SEO issues before they reach production. Try it free β
Automate your workflow with AI
14-day free trial. No charge today. Cancel anytime.
Start Free TrialReady to automate?
Join thousands of teams using BliniBot to automate repetitive tasks. Start free, upgrade anytime.