MediumNo. 0522

Longest Uncommon Subsequence II — LeetCode 522 Python Solution

Topics
Array, Hash Table, Two Pointers, String, Sorting
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

PythonSolution
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

Time
O(n2 × m)where n is the length of the list of strings, and m is the average length of the strings
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
1048Longest String ChainMedium
0532K-diff Pairs in an ArrayMedium
0049Group AnagramsMedium
0349Intersection of Two ArraysEasy
0350Intersection of Two Arrays IIEasy
0692Top K Frequent WordsMedium

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(n2 × 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.

Free to download. Check it runs on your machine, then pick a plan.