Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].

Return true if there is a 132 pattern in nums, otherwise return false.

Input & Output

Example 1 — Found Pattern
$ Input: nums = [1,2,3,4]
Output: false
💡 Note: No 132 pattern exists. The array is strictly increasing, so no element can satisfy nums[i] < nums[k] < nums[j] with i < j < k.
Example 2 — Valid Pattern
$ Input: nums = [3,1,4,2]
Output: true
💡 Note: Pattern found at indices (1,2,3): nums[1]=1, nums[2]=4, nums[3]=2, and 1 < 2 < 4 forms a 132 pattern.
Example 3 — Decreasing Array
$ Input: nums = [-1,3,2,0]
Output: true
💡 Note: Pattern found at indices (0,1,2): nums[0]=-1, nums[1]=3, nums[2]=2, and -1 < 2 < 3 forms a 132 pattern.

Constraints

  • n == nums.length
  • 1 ≤ n ≤ 2 × 104
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
132 Pattern - Two Pass with Minimum Tracking INPUT nums array: 1 i=0 2 i=1 3 i=2 4 i=3 132 Pattern Requirement: Find i < j < k where nums[i] < nums[k] < nums[j] Pattern shape: "1" "3" "2" ALGORITHM STEPS 1 Build min[] array Track minimum from left 1 1 1 1 min[i] = minimum of nums[0..i] 2 Scan right to left Use stack for candidates 3 Check conditions nums[j] > min[j] (potential "3") Pop stack until > min[j] 4 Check for "2" If stack.top < nums[j] --> Found 132 pattern! For [1,2,3,4]: Array is strictly increasing No valid "2" exists between "1" and "3" FINAL RESULT Output: false No 132 pattern exists Why false? Array: 1 < 2 < 3 < 4 (strictly increasing) For 132: need nums[k] < nums[j] where k > j But every later element is LARGER, not smaller! Key Insight: The two-pass approach uses min[] to track potential "1" values and a monotonic stack for "2" candidates. For each position j (potential "3"), we check if stack has a value between min[j] and nums[j]. Time: O(n), Space: O(n). Strictly increasing arrays never have 132 patterns! TutorialsPoint - 132 Pattern | Two Pass with Minimum Tracking Approach
Asked in
Amazon 15 Google 12 Microsoft 8 Facebook 6
89.8K Views
Medium 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