-
Notifications
You must be signed in to change notification settings - Fork 1
/
IB_Arr_Max_Unsorted_subarray.py
64 lines (55 loc) · 1.65 KB
/
IB_Arr_Max_Unsorted_subarray.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from sys import stdin as si
from functools import cmp_to_key
#class Solution:
class Solution:
# @param A : list of integers
# @return a list of integers
def subUnsort_mine(self, A):
X = sorted(A)
s, e = 0, 0
for i in range(len(A)):
if A[i] != X[i]:
s = i
break
for i in range(len(A) - 1, -1, -1):
if A[i] != X[i]:
e = i
break
return [-1] if s == e == 0 else [s, e]
def subUnsort(self, arr):
# if the array has not at least 2 elemets it is sorted
if len(arr) < 2:
return -1
# find the index of the last value
# which is not larger than all previous elements
right = None
l_max = arr[0]
i = 1
while i < len(arr):
if arr[i] < l_max:
right = i
else:
l_max = arr[i]
i += 1
# if none exists the array is already sorted
if not right:
return [-1]
# start from the identified index
# and search for first value which is not smaller
# than all the previous values
left = right - 1
r_min = arr[right]
i = right - 1
while i >= 0:
if arr[i] > r_min:
left = i
else:
r_min = arr[i]
i -= 1
# O_space ( 1 ), O_time( 2*N ) = O(N)
return [left, right]
if __name__ == "__main__":
S = Solution()
test_cases = int(si.readline().strip())
for _ in range(test_cases):
print(S.subUnsort(list(map(int, si.readline().strip().split()))))