We are given an array
A
ofN
lowercase letter strings, all of the same length.Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.
For example, if we have an array
A = ["abcdef","uvwxyz"]
and deletion indices{0, 2, 3}
, then the final array after deletions is["bef","vyz"]
.Suppose we chose a set of deletion indices
D
such that after deletions, the final array has its elements in lexicographic order (A[0] <= A[1] <= A[2] ... <= A[A.length - 1]
).Return the minimum possible value of
D.length
.Example 1:
1 2 3 4 5 6 Input: ["ca","bb","ac"] Output: 1 Explanation: After deleting the first column, A = ["a", "b", "c"]. Now A is in lexicographic order (ie. A[0] <= A[1] <= A[2]). We require at least 1 deletion since initially A was not in lexicographic order, so the answer is 1.Example 2:
1 2 3 4 5 6 Input: ["xc","yb","za"] Output: 0 Explanation: A is already in lexicographic order, so we don't need to delete anything. Note that the rows of A are not necessarily in lexicographic order: ie. it is NOT necessarily true that (A[0][0] <= A[0][1] <= ...)Example 3:
1 2 3 4 Input: ["zyx","wvu","tsr"] Output: 3 Explanation: We have to delete every column.
Solution
Let’s solve it in a greedy approach. We can simply select the columns that make the array sorted.
1
2
3
4
5
6
7
8
9
10
11
12
13
delCol :: [String] -> [String] -> [String]
delCol arr tmp
| null (head arr) = tmp
| otherwise = delCol (map (drop 1) arr) $ if sorted trial then trial else tmp
where
sorted xs = and $ zipWith (<=) xs (tail xs)
trial = zipWith (++) tmp $ map (take 1) arr
sortByDelCol :: [String] -> Int
sortByDelCol [] = 0
sortByDelCol [x] = 0
sortByDelCol arr = diffLen arr $ delCol arr [ "" | x <- arr ]
where diffLen = (-) `on` (length . head)
Here, tmp
is used to store our selection of columns and trial
is the next column to be selected. Since we want our list to be sorted in lexicographic order, we take the next columns if these columns are sorted, otherwise we just move on to the next iteration.
Complexity Analysis
Let \(m\) be the number of elements in the array and \(n\) be the number of characters in each element.
Making a trial takes \(O(mn)\) because both zipWith
and map
take linear time. Moreover, we are iterating over the length of the element \(n\) in the array. Thus, the overall time complexity is \(O(mn^2)\).
The space complexity is simply \(O(mn)\).
Comments powered by Disqus.