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
132 Pattern: Stock Trading AnalogyEntry (1)Peak (3)Sell (2)Trading Strategy (132 Pattern)๐ŸŽฏ Find: Low entry price < Moderate sell price < High peak price๐Ÿ“ˆ Stack tracks potential peaks while scanning right-to-left๐Ÿ’ฐ When entry < best sell price, we found profitable pattern!โšก Time: O(n), Space: O(n) - Each price checked once
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)

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

In worst case, all elements could be stored in the stack

n
2n
โšก Linearithmic Space

Constraints

  • n == nums.length
  • 1 โ‰ค n โ‰ค 2 ร— 104
  • -109 โ‰ค nums[i] โ‰ค 109
  • The array can contain duplicate values
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
67.3K Views
Medium-High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen