Problem 944

Abstract / Summary

Remove columns so each remaining row's letters are in order from left to right.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0944.py

class Solution:
    def minDeletionSize(self, strs: List[str]) -> int:
        result = 0

        size = len(strs[0])
        for i in range(size):
            other = sorted(strs, key = lambda x : x[i])
            if strs != other:
                result += 1

        return result
11 lines | 297 bytes | submitted December 19, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 78% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method minDeletionSize that receives a list of equal-length strings and returns the count of columns that must be removed so that each remaining column is sorted lexicographically from top to bottom. The algorithm iterates over each character position, sorts the original list based on that column, and compares the sorted order with the original order to decide whether the column violates the required monotonicity.

Key Steps

Initialization

result = 0
size = len(strs[0])

The variable result accumulates the number of columns that need deletion. size captures the length of any string in the input, assuming the list is non-empty and all strings share the same length.

Column-wise Examination

for i in range(size):
    other = sorted(strs, key = lambda x : x[i])
    if strs != other:
        result += 1

The loop iterates over each column index i. For each column, the code creates a new ordering other by sorting the original list strs using a key function that extracts the character at position i. If the sorted ordering differs from the original ordering, the column is considered unsorted and the counter result is incremented.

Return Value

return result

After processing all columns, the method returns the total count of columns identified as unsorted.

Edge Cases Handled

When the input list contains a single string, the loop still executes for each character position, but the sorting operation yields the same single-element list, so result remains zero, correctly indicating that no deletions are required.

If all columns are already sorted, the comparison strs != other never holds true, and the method returns zero, reflecting that the input already satisfies the condition.

When the input list is empty, the code would raise an exception at len(strs[0]); however, the design assumes a non-empty list, which aligns with the problem constraints that guarantee at least one string.

Performance Optimizations Observed

The algorithm leverages Python’s built-in sorted function with a custom key, which is implemented in C and therefore executes faster than a pure Python sorting routine. By sorting the entire list for each column rather than performing pairwise comparisons across rows, the code reduces the number of explicit element-wise checks, relying on the highly optimized sorting algorithm to detect any disorder in a single pass per column.

The use of a lambda expression as the key function ensures that the character extraction for each string occurs only once per comparison inside the sort, avoiding repeated indexing operations outside the sorting routine. This compact approach minimizes overhead in the inner loop.

Overall, the method processes each column independently, allowing the Python interpreter to reuse the same sorting infrastructure without additional data structures, which keeps memory usage modest throughout execution.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a row of blocks standing in a line, where each block has a secret word written on it. Some of the words have letters stacked on top of each other like a tall tower. To keep things neat and tidy, the letters in every column of those towers must be in alphabetical order, just like the alphabet song goes.

This code acts like a polite helper looking at each column one by one. It picks up a column of letters and checks if they are perfectly sorted from a to z. If a column is messy and has letters out of order, the helper counts that as a column that needs to be taken away. By checking every single column and keeping track of how many messy ones are found, the code figures out how many columns must be removed so that everything left behind is in the correct order.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 5 | μ = 5.00 | σ = 1.75

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java C# Python Go Rust TS
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
lzl124631x C++
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
lzl124631x C++
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
withaarzoo C++
40 links | 24 authors | 10 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

11 solutions   December 19, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality