Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([])"
Output: true
Example 5:
Input: s = "([)]"
Output: false
Constraints:
1 <= s.length <= 104s consists of parentheses only '()[]{}'.Why this is a Stack / Monotonic Stack problem
A monotonic stack maintains elements in strictly increasing or decreasing order as you push. When a new element violates the order, you pop until the order is restored. This gives O(n) solutions to problems that would naively require O(nΒ²) comparisons β like "next greater element", "largest rectangle in histogram", "daily temperatures".
Push an element. Before pushing, pop everything that your new element "beats" (is greater than for increasing stack, less than for decreasing). Those popped elements have found their answer.
For "next greater element": scan left-to-right. Maintain a stack of elements waiting for their "next greater". When you encounter a new element X, it is the "next greater" for all stack elements smaller than X β so pop them and record X as their answer. Push X itself and wait.
From brute force to optimal β understand every step of the journey
Each element is pushed once and popped once β O(n) total operations despite the while loop inside the for loop. The key realization: when you push element X onto an increasing stack, you've already ensured everything below X in the stack is greater than X. So X is "waiting" for something greater. This amortized O(1) per element is the core efficiency.