You are given a list of whole numbers, nums. A 132 pattern is three positions i < j < k whose values are ordered like the digits of 132: nums[i] < nums[k] < nums[j]. The first is the smallest, the middle one is the largest, and the last sits strictly between them.
Return true if nums has a 132 pattern anywhere, and false if it does not. The three positions do not need to be next to each other.
Example 1
Input: nums = [3, 5, 0, 3, 4] Output: true Why: 3, then 5, then 4: 3 < 4 < 5
2 more examples and the constraints
Example 2
Input: nums = [5, 6, 7] Output: false Why: the values only go up, so nothing comes back down
Example 3
Input: nums = [-2, 4, -1] Output: true Why: −2 < −1 < 4
Constraints
- 1 ≤ length of nums ≤ 200,000
- −1,000,000,000 ≤ nums[i] ≤ 1,000,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Best 1 for every middleO(n²)
- Monotonic stack from the rightO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 200,000 numbers | Verdict |
|---|---|---|---|
| Best 1 for every middle | O(n²) | Good start; too slow | |
| Monotonic stack from the right | O(n) | Best; one pass |
n = how many numbers are in the list.
Edge cases to test
- Fewer than three numbers. [1] or [2, 1] can never hold a pattern: false.
- Only going up. [5, 6, 7]: there is never a smaller value after a bigger one, so false.
- Equal values. [1, 3, 3] is false: the 2 must be strictly below the 3, and [1, 1, 2] fails too.
- Negative numbers. [-2, 4, -1] is true; the comparisons work the same below zero.
- Pattern far apart. The three positions can be spread out, like the 3, 5 and 4 in [3, 5, 0, 3, 4].
Common mistakes
- Requiring the three positions to be next to each other.
- Using ≤ instead of <, which accepts equal values as a pattern.
- Scanning left to right with a stack and losing track of which values are still to the right.
How to talk through it
- 1Clarify. Must the positions be next to each other? Are the comparisons strict?
- 2Give the brute force. Keep the smallest value before j as the 1 and try every k: O(n²).
- 3Flip the direction. From the right, a bigger value pops smaller ones; each pop is a 3 with its 2.
- 4Code the stack. Track the largest popped value as third; any x below it is the 1.
- 5Test out loud. Run an increasing list, a case with equal values and Example 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?