Problem 521

Abstract / Summary

Find the length of the longest uncommon subsequence between two strings if one is not a subsequence of the other.

Note

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

Python 0521.py

class Solution:
    def findLUSlength(self, a: str, b: str) -> int:
        if a == b:
            return -1
        # even though parts might be common, the longest whole sequence is never part of the shorter
        # if same length, then they can't be identical because of the check in the previous code line
        return max(len(a), len(b))
7 lines | 354 bytes | submitted September 13, 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 63% (200k+ submissions).

Typical patterns to solve this problem:
  • 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 single method findLUSlength that determines the length of the longest uncommon subsequence (LUS) between two input strings a and b. The logic is concise: it first checks whether the strings are identical and, if so, returns -1 to indicate that no uncommon subsequence exists. Otherwise, it returns the length of the longer string, because the longer string itself cannot be a subsequence of the shorter one, guaranteeing it as an uncommon subsequence.

Key Steps

The method consists of three logical blocks, each represented by a short code fragment.

The first block establishes the method signature and the early equality test:

def findLUSlength(self, a: str, b: str) -> int:
    if a == b:
        return -1

If the two strings are exactly the same, the function terminates immediately with -1. This early exit prevents any further computation when the answer is already known.

The second block contains a comment that explains the reasoning behind the final return value. Although the comment is not executed, it clarifies the algorithmic insight that the longest whole sequence cannot be part of the shorter string, and that identical strings have already been filtered out.

The third block computes and returns the length of the longer string:

    return max(len(a), len(b))

By using the built-in max function on the lengths of a and b, the method selects the larger of the two values and returns it directly as the LUS length.

Edge Cases Handled

The equality check if a == b: explicitly covers the scenario where both input strings are identical, regardless of their length. In this situation, any subsequence of one string is also a subsequence of the other, so the function correctly returns -1.

When the strings have the same length but differ in at least one character, the equality test fails, and the max call returns that common length. Because the strings are not identical, each string is an uncommon subsequence of the other, and the length of either string is the correct answer.

If one string is empty and the other is non-empty, the equality test is false, and max(len(a), len(b)) yields the length of the non-empty string. An empty string cannot be an uncommon subsequence of a non-empty string, while the non-empty string cannot be a subsequence of the empty one, so the returned length is appropriate.

When both strings are empty, the equality test succeeds, and the method returns -1. This aligns with the definition that there is no uncommon subsequence when both inputs are identical empty strings.

Performance Optimizations

The implementation achieves optimal performance by avoiding any iterative processing of the input strings. The equality comparison a == b operates in linear time relative to the length of the strings, but it is performed only once. The subsequent max(len(a), len(b)) call accesses the precomputed length attributes of the strings, which are constant-time operations in Python. Consequently, the method executes in constant additional overhead beyond the initial equality check.

By returning immediately after the equality test, the function eliminates unnecessary work for the most common trivial case where the inputs match. This early exit pattern reduces the overall execution path length and minimizes function call overhead.

The use of built-in functions (max and len) leverages CPython’s highly optimized native implementations, ensuring that the computation incurs minimal interpreter overhead. No auxiliary data structures are allocated, and the method’s memory footprint remains fixed regardless of input size.

written by openai gpt

ELI5 - Simplified Explanation

Imagine holding two secret letter puzzles. The code looks at these two puzzles to see which one is the biggest secret. First, it checks if the puzzles are exactly the same. If they are identical, it decides there is no special secret that only one has, so it says that nothing works. If the puzzles are different, it measures how many letters are in each one. It picks the longest one because if you have a very long string of letters, it is impossible for the other shorter string to be hidden perfectly inside it as a matching set. The code just points at the winner that has the most letters.

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 = 8 | μ = 8.15 | σ = 1.35

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++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Rust Python Java Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
lzl124631x C++
muhammadfarhankt Go
ruoru Rust
suxrobGM C#
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
lzl124631x C++
muhammadfarhankt Go
ruoru Rust
suxrobGM C#
zfang399 C++
34 links | 20 authors | 10 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

14 solutions   September 13, 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