Asked at 12 companies
12 recent
- Intuit
- Tripadvisor
- Walmart Labs
- BlackRock
- Siemens
- Epic Systems
- Bloomberg
- IBM
- Meta
+2 moreShow fewer
- tcs
- Amazon
Community-reported · source · updated 2026-11-18. ● asked in the last 6 months.
Go step by step: try it yourself before the video and the visual. Progress saves on this device.
0 / 110 pointsSolved (Easy) 0/20Reviews 0/50Mastered 0/25Practice steps 0/15
Step 1
Know these before you start
Practise each one here, or tick what you already know
Step 2
Try it on paper
5–10 minutes, no code yet
In the wild · Undo and the back button: Every action is pushed on a stack; undo pops the latest one. Code editors use a stack the same way to check that brackets match.
ProblemProblem statementGiven a string S containing only the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. A valid string requires opening brackets to be closed by the same type of bracket and in the correct order.ReadHide
Problem Description
Given a string S containing only the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. A valid string requires opening brackets to be closed by the same type of bracket and in the correct order.
Code it here
Tab / Shift+Tab indent · ⌘/Ctrl+/ comments · ⌘/Ctrl+Enter runs · Esc leaves the editor
Step 6
Get it accepted
All test cases pass
Step 7
Review it so it sticks
Re-solve from memory after
The step that matters most: without reviews most of a solved problem fades within weeks. Three short re-solves, each just as you start to forget, are what make it yours.
Your notes
Three lines in your own words. They come back with this problem's reviews, so you can check yourself after recalling the solution.
Solve it yourself before you look
Reading the solution first feels like progress, but it makes the next similar problem — and the interview version — much harder, because you skipped the part where you figure it out. Give it an honest 20–30 minutes. Stuck? Re-read the pattern, watch the concept video, or try the brute force first.
Hidden: approach · solution code · optimal solution
Approach
Use a Stack to store opening brackets. Use a Hash Map for O(1) lookup to find the matching opener when a closing bracket is encountered.
Approaches
1. Stack and Hash Map (Optimal) - O(N) ⭐
Idea: The Stack is the perfect data structure for validating LIFO (Last-In, First-Out) order constraints like nesting.
- Initialize an empty Stack.
- Initialize a Hash Map mapping closers to openers (e.g., `'}' \to '{'$).
- Iterate through the string: push openers onto the stack. When a closer is found, pop the stack and check for a match using the Hash Map.
Time: O(N) (Each character is pushed/popped at most once).
Space: O(N) (Worst case: stack stores all opening brackets).
Solution code
import sys
class Solution:
# Optimized: O(N) Time, O(N) Space - Stack and Hash Map (Dictionary)
def isValid_optimal(self, s: str) -> bool:
# Dictionary for O(1) lookup: closer -> opener
mappings = {')': '(', '}': '{', ']': '['}
stack = []
for char in s:
if char in mappings.values():
# Case 1: Opener -> Push to stack
stack.append(char)
elif char in mappings.keys():
# Case 2: Closer
# If stack is empty (unmatched closer) or mismatch
if not stack or stack.pop() != mappings[char]:
return False
# Ignore other characters
# Final check: Must be empty
return not stack
def solve(self):
try:
s = sys.stdin.readline().strip()
except:
return
result = self.isValid_optimal(s)
print("true" if result else "false")
if __name__ == "__main__":
Solution().solve()Other ways to solve it
- Thought of another approach (slower, or cleverer)? Code it here: the same tests check any approach.
- Community solutions on LeetCode ↗ for many more versions, in many languages. Read them after you've solved it.
Revising this one?
- →Solve it from memory before peeking
- →Say the pattern out loud, not just the code
- →Explain it like you would to a friend
- →Try it again in a different language