456. 132 Pattern
Problem
Decide whether nums contains a "132 pattern": indices i < j < k with nums[i] < nums[k] < nums[j].
Example: [3,1,4,2] → true (1, 4, 2); [1,2,3,4] → false
Constraints: n ≤ 2·10⁵.
Scan from the right keeping a decreasing stack of candidates for "3" and two = the best "2" (largest value popped, i.e. smaller than some later-left "3"). If the current number is less than two, it's a valid "1".
Complexity: O(n).
class Solution:
def find132pattern(self, nums: List[int]) -> bool:
st, two = [], float("-inf")
for x in reversed(nums):
if x < two:
return True
while st and st[-1] < x:
two = st.pop() # x acts as "3", popped value as "2"
st.append(x)
return False
assert Solution().find132pattern([1, 2, 3, 4]) is False
assert Solution().find132pattern([3, 1, 4, 2]) is True
assert Solution().find132pattern([-1, 3, 2, 0]) is True
class Solution {
public boolean find132pattern(int[] nums) {
Deque<Integer> st = new ArrayDeque<>();
long two = Long.MIN_VALUE;
for (int i = nums.length - 1; i >= 0; i--) {
if (nums[i] < two) return true;
while (!st.isEmpty() && st.peek() < nums[i]) two = st.pop();
st.push(nums[i]);
}
return false;
}
}
func find132pattern(nums []int) bool {
st, two := []int{}, math.MinInt
for i := len(nums) - 1; i >= 0; i-- {
x := nums[i]
if x < two {
return true
}
for len(st) > 0 && st[len(st)-1] < x {
two = st[len(st)-1] // x acts as "3", the popped value as "2"
st = st[:len(st)-1]
}
st = append(st, x)
}
return false
}