Problem 955

Abstract / Summary

Remove the fewest columns so that the remaining rows are each sorted in non-decreasing order.

Note

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

Python 0955.py

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

        result  = 0
        ordered = [ "" ] * size
        for i in range(length):
            # add a letter
            for j in range(size):
                ordered[j] += strs[j][i]

            ok = all(ordered[k - 1] <= ordered[k] for k in range(1, size))
            if not ok:
                # delete that letter
                result += 1
                for j in range(size):
                    ordered[j] = ordered[j][:-1]

        return result
20 lines | 611 bytes | submitted October 26, 2023 | GitHub   13% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • 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 solves the problem of determining the minimum number of columns that must be removed from a list of equal-length strings so that the remaining columns form a set of strings sorted lexicographically from top to bottom. The algorithm proceeds column by column, building the prefixes of each string incrementally and checking whether the current set of prefixes preserves the required order. When a column would break the ordering, it is counted as a deletion and the temporary prefixes are rolled back.

Core Logic

The function begins by extracting the length of a single string and the total number of strings. These values are stored in the variables length and size.

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

A counter result is initialized to zero; it will accumulate the number of columns that need to be deleted. An auxiliary list ordered of length size is created, each entry starting as an empty string. This list holds the progressively built prefixes for each row.

result  = 0
ordered = [ "" ] * size

The outer loop iterates over each column index i from 0 to length-1. For each column, the inner loop appends the character at position i from every string to the corresponding entry in ordered. This step constructs the new prefixes that would result if the current column were kept.

for i in range(length):
    for j in range(size):
        ordered[j] += strs[j][i]

After the characters are added, the algorithm verifies whether the updated prefixes remain in non-decreasing lexicographic order. This verification uses a generator expression that compares each adjacent pair of prefixes.

ok = all(ordered[k - 1] <= ordered[k] for k in range(1, size))

If the ordering condition fails, the column is deemed unsuitable. The counter result is incremented, and the most recently added character is removed from every prefix, effectively discarding the column.

if not ok:
    result += 1
    for j in range(size):
        ordered[j] = ordered[j][:-1]

When the loop finishes processing all columns, result holds the minimal number of deletions required, and it is returned.

return result

Edge Cases Handled

The algorithm gracefully handles the situation where the input list contains only a single string. In that case, the inner ordering check always succeeds because there are no adjacent pairs to compare, resulting in zero deletions.

When all columns are already ordered, the ok condition remains true for every iteration, and the function returns zero without performing any rollback.

If a column causes a violation early in the sequence, the rollback removes only the characters added during that specific iteration, leaving earlier columns untouched. This ensures that previously validated columns are never inadvertently discarded.

The code also works correctly when the strings contain repeated characters. Since the comparison uses <=, equal prefixes are considered ordered, allowing columns that produce identical characters across rows to be retained.

Performance Optimizations

The implementation avoids constructing full intermediate strings for each column by reusing the ordered list and appending characters in place. This incremental building reduces the amount of temporary memory allocation compared to recreating the entire set of prefixes on each iteration.

The rollback step removes only the last character from each prefix using slicing (ordered[j][:-1]). This operation is efficient because it works on the existing string objects rather than rebuilding them from scratch.

The ordering check leverages Python’s built-in all function combined with a generator expression. This approach short-circuits as soon as a violation is detected, preventing unnecessary comparisons for the remaining rows in that column.

By iterating column-wise rather than row-wise, the algorithm ensures that each character of the input is examined exactly once for addition and at most once for removal, keeping the overall processing tight and predictable.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a row of blocks standing next to each other. Each block has a column of letters stacked up high, like a little tower. The goal is to make sure every word in the tower is in alphabetical order from top to bottom.

First, look at the first column of letters. Think of these as a new set of building blocks. Every row has a character that needs to be added to a special list to see if the letters stay in the right order.

After grabbing a letter for every row, compare them. If the letters in the column follow the alphabet correctly, keep them there and move on to the next column. If the letters are out of place, that column is like a messy pile of blocks. When the pile is messy, take those letters away and count that column as a deletion. Keep doing this for every column until finished. Each time a column is removed, it adds one to the final count of removed parts.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 6.07 | σ = 1.54

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

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++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python Java Go Rust TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
wisdompeak C++
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
wisdompeak C++
withaarzoo C++
27 links | 14 authors | 8 languages

Videos

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

Solved On The Same Day

2 easy 4 medium
7 solutions   October 26, 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