Stack-Based Approach to Detect 132 Pattern #345
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Intuition
We are looking for a subsequence in the array that follows the 132 pattern: a sequence where there exists indices
i < j < k
such thatnums[i] < nums[k] < nums[j]
. The key is to track the largest '2' in the 132 pattern using a stack.Approach
prev
to store the most recent valid '2' found in the sequence.nums[i]
, check if it is less than the currentprev
('2'). If yes, we've found a valid 132 pattern.prev
by popping from the stack, ensuring we always have the largest possible '2'.Complexity
Time complexity:
The time complexity is ( O(n) ), where ( n ) is the size of the input array. Each element is pushed and popped from the stack at most once.
Space complexity:
The space complexity is ( O(n) ) in the worst case, due to the space used by the stack.