Problem 522

Abstract / Summary

Find the length of the longest uncommon subsequence among a list of strings.

Note

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

Python 0522.py

class Solution:
    def findLUSlength(self, strs: List[str]) -> int:
        # a whole string can be a subsequence, too
        # let's find the longest string that isn't a subsequence of any other string
        # it will be faster to check longest strings first

        # shortest words first
        strs.sort(key = lambda x : len(x))

        # find duplicates
        skip = set()
        have = set()
        for s in strs:
            if s in have:
                skip.add(s)
            have.add(s)

        def partOf(long, short): # True if short is a subsequence of long and short != long
            if len(long) < len(short) or long == short: # long == short simplifies the any() construct below
                return False

            # greedy matching of short and long
            l = s = 0
            while l < len(long) and s < len(short):
                if long[l] == short[s]:
                    s += 1
                l += 1
            return s == len(short)

        # compare each string against all longer strings
        for short in reversed(strs):
            if short not in skip and not any([ partOf(long, short) for long in strs ]):
                return len(short)

        return -1
35 lines | 1259 bytes | submitted December 1, 2023 | GitHub   40% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Sorting
  • String
  • Two Pointers
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 program implements a method that receives a list of strings and returns the length of the longest string that is not a subsequence of any other string in the list. If every string appears as a subsequence of another, the method returns -1. The solution proceeds by ordering the input, eliminating duplicates, providing a helper to test the subsequence relation, and then scanning the strings from longest to shortest until a qualifying candidate is found.

Key Steps

Sorting by length

The first operation arranges the strings in non-decreasing order of their lengths.

strs.sort(key = lambda x : len(x))

By placing shorter strings before longer ones, the later scan can examine candidates from longest to shortest simply by iterating the sorted list in reverse. This ordering guarantees that once a string is identified as uncommon, no longer string can invalidate the result.

Detecting duplicates

A duplicate string can never be an uncommon subsequence because it appears at least twice in the input. The code builds two sets: one to record strings that have been seen and another to record those that appear more than once.

skip = set()
have = set()
for s in strs:
    if s in have:
        skip.add(s)
    have.add(s)

The skip set later prevents any duplicated string from being considered as a candidate.

Subsequence checking helper

The nested function partOf determines whether a shorter string is a proper subsequence of a longer string. It first rejects cases where the lengths make a subsequence impossible or where the strings are identical, then performs a greedy linear scan.

def partOf(long, short): # True if short is a subsequence of long and short != long
    if len(long) < len(short) or long == short:
        return False
    l = s = 0
    while l < len(long) and s < len(short):
        if long[l] == short[s]:
            s += 1
        l += 1
    return s == len(short)

The greedy scan advances the pointer in the short string only when a matching character is found, ensuring that the relative order of characters is respected.

Main search loop

The core of the algorithm iterates over the strings from longest to shortest, skipping any that were marked as duplicates. For each candidate, it checks whether any longer string contains it as a subsequence using the helper. If none do, the length of that candidate is returned immediately.

for short in reversed(strs):
    if short not in skip and not any([ partOf(long, short) for long in strs ]):
        return len(short)
return -1

The any construct short-circuits as soon as a single longer string is found that contains the candidate, avoiding unnecessary checks.

Edge Cases Handled

When the input list is empty, the final return -1 is executed because the loop body never runs, correctly indicating that no uncommon subsequence exists.

If every string in the list is identical, the duplicate detection step places that string in the skip set, causing the main loop to ignore it and fall through to the -1 return.

When multiple strings share the same maximum length, the reverse iteration examines them in the order they appear after sorting. Because the duplicate set excludes exact repeats, any distinct longest string that is not a subsequence of another will be returned.

The helper function explicitly returns False when the two strings are equal, ensuring that a string is not considered a subsequence of itself. This prevents a self-match from incorrectly disqualifying a candidate.

If a shorter string is a subsequence of several longer strings, the any call stops at the first match, avoiding redundant work. Conversely, if a shorter string is not a subsequence of any longer string, the loop proceeds through all longer strings to confirm the condition before returning the length.

Performance Optimizations

Sorting the input by length enables the algorithm to consider candidates from longest to shortest without additional indexing structures. This ordering reduces the number of subsequence checks because once a qualifying string is found, the method can return immediately.

Using two hash sets for duplicate detection provides constant-time membership tests, allowing the algorithm to filter out repeated strings before the expensive subsequence checks begin.

The partOf function employs a linear greedy scan that runs in time proportional to the sum of the lengths of the two strings being compared, and it exits early as soon as the short string is fully matched.

The any expression is built around a list comprehension, but Python’s evaluation of any short-circuits on the first True result, preventing the helper from being invoked on every longer string when a match is found early.

Finally, the reverse iteration over the sorted list eliminates the need for an explicit index or separate collection of longer strings; each iteration naturally treats the current element as the candidate and all elements in the original list as potential supersets, simplifying the control flow and reducing overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big box of word cards and you want to find the longest one that is truly special. A word is special if you cannot build it by picking letters out of any other word in the box while keeping them in the same order. For example, if you have a card that says cat, you could build it from the word catalog, so cat would not be special in that group.

The code starts by lining the words up from shortest to longest. It looks for words that are exactly the same, because if two words match perfectly, they can never be the longest unique one. After putting the matching words aside, the computer looks at the longest words first. It creates a little rule to see if a small word is hidden inside a longer word. It goes through the letters of the long word one by one to see if it can find all the letters of the small word in order. If it checks a long word and sees that it is not hiding inside any of the other words in the box, then it knows it has found the winner. The computer measures how many letters are on that special card and shouts out the number.

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 = 7 | μ = 6.56 | σ = 1.50

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

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

6 solutions   December 1, 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