-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdelete-columns-to-make-sorted.py
84 lines (75 loc) · 2.53 KB
/
delete-columns-to-make-sorted.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# 944. Delete Columns to Make Sorted
# 🟢 Easy
#
# https://leetcode.com/problems/delete-columns-to-make-sorted/
#
# Tags: Array - String
import timeit
from typing import List
# Iterate over the columns, then a nested loop iterates over the strings
# after the first one comparing that string/column character with the
# one on the same position on the previous string, if we find one
# character that does not follow the lexicographical order, we add one
# to the result and break out of the column loop.
#
# Time complexity: O(m*n) - We will visit each character in each string
# in the input.
# Space complexity: O(1) - Constant extra memory used.
#
# Runtime 162 ms Beats 75.16%
# Memory 14.5 MB Beats 93.5%
class Iterative:
def minDeletionSize(self, strs: List[str]) -> int:
res = 0
# Iterate over all columns.
for j in range(len(strs[0])):
# Iterate over all strings except the first.
for i in range(1, len(strs)):
if strs[i][j] < strs[i - 1][j]:
res += 1
break
return res
# Use zip to rearrange the strings into lists corresponding to the
# columns, then check that each character has a lexicographical value
# equal or more than the preceding one.
#
# Time complexity: O(m*n) - We will visit each character in each string
# in the input.
# Space complexity: O(m*n) - The zip(*strs) expression makes a copy of
# the input in memory.
#
# Runtime 129 ms Beats 91.16%
# Memory 14.6 MB Beats 61.89%
class BuiltIn:
def minDeletionSize(self, strs: List[str]) -> int:
return sum(
any(col[i - 1] > col[i] for i in range(1, len(col)))
for col in zip(*strs)
)
def test():
executors = [
Iterative,
BuiltIn,
]
tests = [
[["a", "b"], 0],
[["zyx", "wvu", "tsr"], 3],
[["cba", "daf", "ghi"], 1],
]
for executor in executors:
start = timeit.default_timer()
for _ in range(1):
for col, t in enumerate(tests):
sol = executor()
result = sol.minDeletionSize(t[0])
exp = t[1]
assert result == exp, (
f"\033[93m» {result} <> {exp}\033[91m for"
+ f" test {col} using \033[1m{executor.__name__}"
)
stop = timeit.default_timer()
used = str(round(stop - start, 5))
cols = "{0:20}{1:10}{2:10}"
res = cols.format(executor.__name__, used, "seconds")
print(f"\033[92m» {res}\033[0m")
test()