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]
. Find whether any 132 pattern exists in nums
.
n
(the length of the array)?nums
?For the sake of this problem, we will assume:
nums
can range from 1 to 100,000.nums
can range between -10^9
and 10^9
.To find the 132 pattern, we need to find three indices i, j, and k such that:
i < j < k
nums[i] < nums[k] < nums[j]
A straightforward solution with three nested loops would be too slow (O(n^3) time complexity). Instead, we can use a more efficient approach with a combination of arrays/stacks to keep track of potential candidates for the 132 pattern.
minArray
where minArray[i]
stores the minimum value in nums
from index 0 to i. This helps us keep track of the smallest value (candidate for nums[i]) before the current element.nums[k]
values (which must be less than the current nums[j]
but greater than the minimum value up to that point).Here’s a step-by-step outline:
minArray
such that minArray[i]
is the minimum value in nums[0:i+1]
j
), maintaining a stack for possible values of nums[k]
nums[j]
, ensure that we pop elements from the stack that are less than minArray[j]
(as they cannot satisfy the 132 pattern condition)minArray[j]
and less than nums[j]
, then we have found a valid 132 pattern.Here’s the Java code to implement this strategy:
import java.util.Stack;
public class Solution {
public boolean find132pattern(int[] nums) {
if (nums.length < 3) return false;
// Step 1: Create minArray
int[] minArray = new int[nums.length];
minArray[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
minArray[i] = Math.min(minArray[i-1], nums[i]);
}
// Step 2: Traverse from right to left to find 132 pattern
Stack<Integer> stack = new Stack<>();
for (int j = nums.length - 1; j >= 0; j--) {
if (nums[j] > minArray[j]) {
while (!stack.isEmpty() && stack.peek() <= minArray[j]) {
stack.pop();
}
if (!stack.isEmpty() && stack.peek() < nums[j]) {
return true;
}
stack.push(nums[j]);
}
}
return false;
}
}
minArray
takes O(n) time.nums
from right to left while using the stack operations takes O(n) time.minArray
and the stack both require O(n) space.This solution is efficient and should perform well for the given problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?