132 Pattern - Problem
You're given an array of integers, and your mission is to find a special pattern called a 132 pattern. This pattern consists of three elements at positions i, j, and k where:
i < j < k(they appear in this order in the array)nums[i] < nums[k] < nums[j](the values follow a 1-3-2 relationship)
Think of it as finding a "dip and recover" pattern: a small number, followed by a large peak, then a medium number that's between them.
Example: In array [1, 2, 3, 4], there's no 132 pattern. But in [3, 1, 4, 2], we have 1 < 2 < 4 forming our 132 pattern!
Goal: Return true if such a pattern exists, false otherwise.
Input & Output
example_1.py โ Basic Pattern Found
$
Input:
[1, 2, 3, 4]
โบ
Output:
false
๐ก Note:
No 132 pattern exists. The array is strictly increasing, so we cannot find i < j < k where nums[i] < nums[k] < nums[j].
example_2.py โ Pattern Exists
$
Input:
[3, 1, 4, 2]
โบ
Output:
true
๐ก Note:
132 pattern found: i=1, j=2, k=3 where nums[1]=1, nums[2]=4, nums[3]=2, and 1 < 2 < 4 satisfies the pattern.
example_3.py โ Decreasing Array
$
Input:
[-1, 3, 2, 0]
โบ
Output:
true
๐ก Note:
132 pattern found: i=0, j=1, k=2 where nums[0]=-1, nums[1]=3, nums[2]=2, and -1 < 2 < 3 satisfies the pattern.
Visualization
Tap to expand
Understanding the Visualization
1
Scan Market History
Look at price data from most recent to oldest (right to left scanning)
2
Track Peak Prices
Use a stack to remember significant peak prices in descending order
3
Identify Sell Points
When a new peak appears, previous peaks become potential sell points
4
Find Entry Point
Look for prices lower than our best sell point - that's our 132 pattern!
Key Takeaway
๐ฏ Key Insight: Scan right-to-left using a monotonic stack to efficiently track potential peaks while maintaining the best middle value for pattern detection.
Time & Space Complexity
Time Complexity
O(n)
Each element is pushed and popped from stack at most once, so amortized O(n)
โ Linear Growth
Space Complexity
O(n)
In worst case, all elements could be stored in the stack
โก Linearithmic Space
Constraints
- n == nums.length
- 1 โค n โค 2 ร 104
- -109 โค nums[i] โค 109
- The array can contain duplicate values
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code