|
| 1 | +# [Problem 944: Delete Columns to Make Sorted](https://leetcode.com/problems/delete-columns-to-make-sorted/description/?envType=daily-question) |
| 2 | + |
| 3 | +## Initial thoughts (stream-of-consciousness) |
| 4 | +I need to count how many columns (positions across all strings) are not sorted top-to-bottom. The strings all have the same length, so I can iterate column indices 0..m-1 and check that character at row i is <= character at row i+1 for all adjacent rows. If any adjacent pair violates that, the column must be deleted. |
| 5 | + |
| 6 | +In Python a neat trick is to use zip(*strs) to iterate columns as tuples. For each column tuple, check whether it's non-decreasing. Alternatives: build each column string and compare it to its sorted version, or check adjacent pairs directly. The simplest is checking adjacent pairs to allow early exit when a violation is found. |
| 7 | + |
| 8 | +## Refining the problem, round 2 thoughts |
| 9 | +Edge cases: |
| 10 | +- Only one row (n = 1) — every column is trivially sorted, so answer is 0. |
| 11 | +- All columns unsorted — count equals length of strings. |
| 12 | +- Performance: n up to 100, m up to 1000, so an O(n * m) solution is fine. |
| 13 | + |
| 14 | +Choice between implementations: |
| 15 | +- zip(*strs) + any(previous > current for pairs) is clean and avoids creating additional large structures per column. |
| 16 | +- Comparing column to sorted(column) is also easy but creates a new list for sorting (slightly more overhead). |
| 17 | + |
| 18 | +Time complexity: O(n * m) where n = number of strings, m = length of each string. |
| 19 | +Space complexity: O(1) extra (ignoring input) or O(n) per column if considering the tuple created by zip; overall negligible given constraints. |
| 20 | + |
| 21 | +## Attempted solution(s) |
| 22 | +```python |
| 23 | +from typing import List |
| 24 | + |
| 25 | +class Solution: |
| 26 | + def minDeletionSize(self, strs: List[str]) -> int: |
| 27 | + # Count columns that are not sorted top-to-bottom. |
| 28 | + deletions = 0 |
| 29 | + # Iterate over columns using zip to collect column characters |
| 30 | + for col in zip(*strs): |
| 31 | + # If any previous character is greater than the next, column is unsorted |
| 32 | + if any(a > b for a, b in zip(col, col[1:])): |
| 33 | + deletions += 1 |
| 34 | + return deletions |
| 35 | +``` |
| 36 | +- Notes: |
| 37 | + - Approach: iterate columns (zip(*strs)) and check adjacent pairs for order violation; increment count if any violation found. |
| 38 | + - Time complexity: O(n * m) where n = number of strings and m = length of each string (we check each character once). |
| 39 | + - Space complexity: O(1) extra (aside from the temporary tuple for each column produced by zip, which is size n). |
0 commit comments