Longest Uncommon Subsequence II — LeetCode 522 Python Solution

MediumArrayHash TableTwo PointersStringSorting
Problem
#522
Reading time
3 min

The problem

Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1.

Example

Input
strs = ["aba","cdc","eae"]
Output
3

Python solution

Python
class Solution:
    def findLUSlength(self, strs: List[str]) -> int:
        def check(s: str, t: str):
            i = j = 0
            while i < len(s) and j < len(t):
                if s[i] == t[j]:
                    i += 1
                j += 1
            return i == len(s)

        ans = -1
        for i, s in enumerate(strs):
            for j, t in enumerate(strs):
                if i != j and check(s, t):
                    break
            else:
                ans = max(ans, len(s))
        return ans

Complexity

MeasureComplexity
TimeO(n^2 \times m), where n is the length of the list of strings, and m is the average length of the strings
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 522. Longest Uncommon Subsequence II is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 522. Longest Uncommon Subsequence II?
LeetCode 522. Longest Uncommon Subsequence II is rated Medium on LeetCode.
What is the time complexity of LeetCode 522. Longest Uncommon Subsequence II?
The Python solution on this page runs in O(n^2 \times m), where n is the length of the list of strings, and m is the average length of the strings.
What is the space complexity of LeetCode 522. Longest Uncommon Subsequence II?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 522. Longest Uncommon Subsequence II cover?
LeetCode 522. Longest Uncommon Subsequence II is tagged Array, Hash Table, Two Pointers, String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview