132 Pattern
Given an array of nnumsnums[i]nums[j]nums[k]i < j < knums[i] < nums[k] < nums[j]
Return truenumsfalse
Example 1
Output: false
Explanation: There is no 132 pattern in the sequence.
Example 2
Output: true
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
Example 3
Output: true
Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
Constraints:
n == nums.length1 <= n <= 2 * 105-109 <= nums[i] <= 109
Contents
Solution 1 - Using a Stack
The main idea behind this solution is, as per the problem statement i < j < kkinums[k]nums[i] < nums[k] < nums[j]nums[j]nums[i]
When we are at index kjinums[j], nums[i]nums[i] < nums[j]nums[i]nums[j]
import java.util.Stack;
public class Find132Pattern {
static boolean find132pattern(int[] nums) {
Stack<int[]> stack = new Stack<>();
int currentMin = nums[0];
for(int i =1; i<nums.length; i++) {
int current = nums[i];
while(!stack.isEmpty() && current>=stack.peek()[0]) {
stack.pop();
}
if(!stack.isEmpty() && current <stack.peek()[0] && current > stack.peek()[1]) {
return true;
}
stack.push(new int[]{current, currentMin});
currentMin = Math.min(current, currentMin);
}
return false;
}
public static void main(String[] args) {
System.out.println(find132pattern(new int[]{3,1,4,2}));
System.out.println(find132pattern(new int[]{1,2,3,4}));
}
}
Complexity Analysis:
Time complexity: Time complexity for the solution will be O(n) where nnums
Space complexity: O(n) for storing elements into stack.
Above implementations source code can be found at