Skip to content

Commit 68ca440

Browse files
author
agni1402
committed
Added pattern132.java
1 parent 2dd13b5 commit 68ca440

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

pattern132.class

1.41 KB
Binary file not shown.

pattern132.java

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
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].
3+
Return true if there is a 132 pattern in nums, otherwise, return false.
4+
5+
Test Case I:
6+
Input: nums = [1,2,3,4]
7+
Output: false
8+
Explanation: There is no 132 pattern in the sequence.
9+
10+
Test Case II:
11+
Input: nums = [3,1,4,2]
12+
Output: true
13+
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
14+
*/
15+
16+
import java.util.*;
17+
18+
public class pattern132{
19+
private static boolean find132pattern(int[] nums) {
20+
int n = nums.length;
21+
if (n < 3)
22+
return false;
23+
Deque<Integer> decreasingStack = new ArrayDeque<>(n);
24+
int maxThirdElement = Integer.MIN_VALUE;
25+
for (int i = n - 1; i >= 0; i--) {
26+
int currentNumber = nums[i];
27+
if (currentNumber < maxThirdElement)
28+
return true;
29+
while (!decreasingStack.isEmpty() && decreasingStack.peek() < currentNumber) {
30+
maxThirdElement = decreasingStack.pop();
31+
}
32+
decreasingStack.push(currentNumber);
33+
}
34+
return false;
35+
}
36+
public static void main(String[] args){
37+
Scanner sc = new Scanner(System.in);
38+
int n;
39+
System.out.println("Enter the size of the array: ");
40+
n = sc.nextInt();
41+
int[] nums = new int[n];
42+
System.out.println("Enter the elements of the array: ");
43+
for(int i=0; i<n; i++){
44+
nums[i] = sc.nextInt();
45+
}
46+
boolean result = find132pattern(nums);
47+
if(result){
48+
System.out.println("The 132 pattern exixts in an Array");
49+
}else{
50+
System.out.println("The 132 pattern does not exixts in an Array");
51+
}
52+
}
53+
}

0 commit comments

Comments
 (0)