InterviewHubPRO
Section Overview
Q29

Question 29 of 100

Part 4: Stacks, Queues & Monotonic Stacks (29 - 36)

29%
DSA Patterns (Multi-Lang)•Part 4: Stacks, Queues & Monotonic Stacks (29 - 36)

Valid Parentheses.

In Simple Words: Push opening brackets onto stack. For closing brackets, check if stack top matches corresponding opening symbol; if not, string is invalid. Return stack.length === 0 at end.

  • Time: $O(N)$ | Space: $O(N)$
Multi-Language Solutions
Switch tabs or choose All
def isValid(s: str) -> bool:
    stack = []
    close_to_open = {')': '(', '}': '{', ']': '['}
    for c in s:
        if c in close_to_open:
            if stack and stack[-1] == close_to_open[c]:
                stack.pop()
            else:
                return False
        else:
            stack.append(c)
    return len(stack) == 0