Skip to content

Commit 357f056

Browse files
committed
using stack to track the middle element in 132 pattern
1 parent d643ff0 commit 357f056

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

stack/find132pattern.java

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
// O(N) time and O(N) space
3+
public boolean find132pattern(int[] nums) {
4+
if (nums == null || nums.length < 3) return false;
5+
6+
int[] minArray = new int[nums.length];
7+
minArray[0] = nums[0];
8+
for (int i=1; i<nums.length; i++) {
9+
minArray[i] = Math.min(nums[i], minArray[i-1]);
10+
}
11+
Stack<Integer> kStack = new Stack<>(); // stack to keep the middle element 2
12+
kStack.push(nums[nums.length - 1]);
13+
14+
for(int j=nums.length - 1; j>=0; j--) {
15+
while (!kStack.isEmpty() && kStack.peek() <= minArray[j]) {
16+
kStack.pop(); // since k(2) should be greater than j(1)
17+
}
18+
if (!kStack.isEmpty() && kStack.peek() < nums[j]) {
19+
return true;
20+
}
21+
kStack.push(nums[j]);
22+
}
23+
return false;
24+
}
25+
}

0 commit comments

Comments
 (0)