Skip to content

Commit 8511476

Browse files
committed
Array problem
1 parent d1641fa commit 8511476

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

Arrays/sorted_triplet.py

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Problem source: https://practice.geeksforgeeks.org/problems/sorted-subsequence-of-size-3/1
2+
# Sorted subsequence of size 3
3+
4+
from collections import defaultdict
5+
6+
7+
class Solution:
8+
def find3number(self, A, n):
9+
10+
max_a = defaultdict(lambda: -1)
11+
min_a = defaultdict(lambda: -1)
12+
max_e = n - 1
13+
min_e = 0
14+
15+
# for min
16+
for i in range(n):
17+
e = A[i]
18+
if e <= A[min_e]:
19+
min_e = i
20+
min_a[i] = -1
21+
else:
22+
min_a[i] = min_e
23+
24+
for j in range(n - 1, -1, -1):
25+
e = A[j]
26+
if e >= A[max_e]:
27+
max_e = j
28+
max_a[j] = -1
29+
else:
30+
max_a[j] = max_e
31+
32+
for i in range(n):
33+
if min_a[i] != -1 and max_a[i] != -1:
34+
seq = (A[min_a[i]], A[i], A[max_a[i]])
35+
return seq
36+
37+
return []
38+
39+
40+
# {
41+
# Driver Code Starts
42+
# Initial Template for Python 3
43+
44+
import sys
45+
46+
sys.setrecursionlimit(100000)
47+
48+
49+
def isSubSeq(arr, lis, n, m):
50+
if m == 0:
51+
return True
52+
if n == 0:
53+
return False
54+
if arr[n - 1] == lis[m - 1]:
55+
return isSubSeq(arr, lis, n - 1, m - 1)
56+
return isSubSeq(arr, lis, n - 1, m)
57+
58+
59+
t = int(input())
60+
for _ in range(t):
61+
n = int(input())
62+
arr = list(map(int, input().strip().split()))
63+
lis = Solution().find3number(arr, n)
64+
# print(lis)
65+
# print(isSubSeq(arr, lis, n, len(lis)))
66+
if len(lis) != 0 and len(lis) != 3:
67+
print(-1)
68+
continue
69+
if len(lis) == 0:
70+
print(0)
71+
elif lis[0] < lis[1] and lis[1] < lis[2] and isSubSeq(arr, lis, n, len(lis)):
72+
print(1)
73+
else:
74+
print(-1)

0 commit comments

Comments
 (0)