Delete Columns to Make Sorted II LeetCode solution in Python

1
class Solution:
2
def minDeletionSize(self, strs: List[str]) -> int:
3
n = len(strs)
4
col_size = len(strs[0])
5
# a b c d e f g h i j k l m n o p q r s t u v w x y z
6

7
i = 0
8
ans = 0
9

10
def getRemoved(idx):
11
# removing the idx column
12
for x in range(n):
13
strs[x] = strs[x][:idx] + strs[x][idx + 1 :]
14

15
while i < col_size:
16
tmp = strs[0][: i + 1]
17
flag = True
18
similar = False
19

20
for j in range(1, n):
21
if strs[j][: i + 1] < tmp:
22
# previous element is larger ( unsorted )
23
flag = False
24
break
25

26
elif strs[j][: i + 1] > tmp:
27
# previous element is smaller ( sorted )
28
tmp = strs[j][: i + 1]
29

30
else:
31
# previous element is equal ( not clear )
32
tmp = strs[j][: i + 1]
33
similar = True
34

35
if flag == True and similar == False:
36
# all are sorted and we are ready to return ans
37
return ans
38

39
elif flag == True and similar == True:
40
# all are sorted but can't be decided for further columns. check for next col
41
i += 1
42

43
elif flag == False:
44
# unsorted column = removal
45
getRemoved(i)
46
# increment the answer and since we removed i th col decrement col_size
47
ans += 1
48
col_size -= 1
49

50
return ans

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0