↓Skip to main content
  1. LeetCode/

LeetCode 944: Delete Columns to Make Sorted

·1 min· ·
LeetCode Easy Array String Longest-Increasing-Subsequence
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-26

  • Submissions: Wrong Answer ×2 → Accepted

Approach
#

zip(*strs) turns each column into a tuple. A column must be deleted when it is not non-decreasing, i.e. some col[i] > col[i + 1]. Count such columns.

My Attempts
#

  • Attempt 1 forgot the return.
  • Attempt 2 wrote sum(sorted(s) == s ...), counting the sorted columns, the opposite; and since s is a tuple while sorted(s) is a list they never compare equal, so it always returned 0: ["c", "b"] should be 1.
  • sorted(s) != list(s) passed.

Solution
#

class Solution:
    def minDeletionSize(self, strs: List[str]) -> int:
        return sum(any(a > b for a, b in zip(col, col[1:])) for col in zip(*strs))

Complexity
#

Time O(total characters), space O(m).

Mistakes to Avoid
#

  • zip yields tuples while sorted returns a list, so == between them is always false.
  • Count the columns that are not sorted.

Interview Explanation
#

I take each column with zip, check whether any adjacent pair decreases, and count those columns. Time is linear in the total length.

Related

LeetCode 929: Unique Email Addresses
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 929 note: split at @, normalize only the local part (drop everything after +, remove dots), rejoin with the domain and collect in a set
LeetCode 953: Verifying an Alien Dictionary
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 953 note: map letters to their alien index and compare each adjacent pair at the first differing character; with no difference, the shorter must come first
LeetCode 821: Shortest Distance to a Character
·2 mins
LeetCode Easy Array Two-Pointers String
LeetCode 821 note: one left-to-right pass for the distance to the nearest c on the left, then a right-to-left pass taking the minimum
LeetCode 819: Most Common Word
·2 mins
LeetCode Easy Array Hash-Table String Counting
LeetCode 819 note: replace punctuation with spaces, lowercase, split, count, and pick the most frequent word not banned
LeetCode 806: Number of Lines To Write String
·2 mins
LeetCode Easy Array String
LeetCode 806 note: simulate writing, wrapping when the next letter would exceed 100; landing exactly on 100 stays on the line
LeetCode 748: Shortest Completing Word
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 748 note: count the plate’s letters in lowercase, then find the shortest word covering every count, taking the earliest on ties