132 Pattern

Given an array of n integers `nums`, a 132 pattern is a subsequence `nums[i]`, `nums[j]`, `nums[k]` with `i < j < k` and `nums[i] < nums[k] < nums[j]`. Return `true` if there is a 132 pattern in `nums`, otherwise return `false`.

30:00

132 Pattern
medium
Free written solution
Topics
Companies

Given an array of n integers nums, a 132 pattern is a subsequence nums[i], nums[j], nums[k] with i < j < k and nums[i] < nums[k] < nums[j]. Return true if there is a 132 pattern in nums, otherwise return false.

Example 1:
Input: {"nums":[1,2,3,4]}
Output: false
Constraints:
  • n==nums.lengthn == \text{nums.length}

  • 1≤n≤2×1051 \leq n \leq 2 \times 10^5

  • −109≤nums[i]≤109-10^9 \leq \text{nums}[i] \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,3,4]}

Scan from the right. The stack holds candidates for the 3, and third holds the best 2 found so far (none yet, so -inf).

nums, scanned right to left

1

2

3

4

0

1

2

3

current i

on stack

3 (popper)

2 (third)

1 (below third)

stack (bottom to top, decreasing)

empty

Every pop means a bigger value sits to its left, so the popped value is a valid 2. Keeping the largest such 2 gives the 1 the most room.

Variables
VariableValue
i-1
nums[i]null
third-inf
stack[]
DepthFunction Call
Stack empty
0/9