#944
Delete Columns to Make Sorted
EasyArrayStringArrayString
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses the same logic as the brute force but focuses on reducing unnecessary checks by breaking early when an unsorted column is found. This approach is efficient and avoids redundant comparisons.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a counter for unsorted columns.
- 2Step 2: Loop through each column index from 0 to the length of the first string.
- 3Step 3: For each column, loop through each row index from 0 to n-2.
- 4Step 4: If the current character is greater than the next character, increment the counter and break out of the inner loop.
- 5Step 5: Return the counter after checking all columns.
solution.py10 lines
1# Full working Python code
2
3def minDeletionSize(strs):
4 unsorted_count = 0
5 for col in range(len(strs[0])):
6 for row in range(len(strs) - 1):
7 if strs[row][col] > strs[row + 1][col]:
8 unsorted_count += 1
9 break
10 return unsorted_countℹ
Complexity note: The time complexity is O(n) because we are only iterating through each column once and breaking early when we find an unsorted column. The space complexity remains O(1) as we are using a constant amount of extra space.
- 1Columns must be checked independently for sorting.
- 2Breaking early can save unnecessary checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.