Longest Uncommon Subsequence I — LeetCode 521 Python Solution
EasyString
- Problem
- #521
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given two strings a and b, return the length of the longest uncommon subsequence between a and b. If no such uncommon subsequence exists, return -1.
Example
- Input
- a = "aba", b = "cdc"
- Output
- 3
- Explanation
- One longest uncommon subsequence is "aba" because "aba" is a subsequence of "aba" but not "cdc".
Python solution
Python
class Solution:
def findLUSlength(self, a: str, b: str) -> int:
return -1 if a == b else max(len(a), len(b))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the longer string among `a` and `b` |
| Space | O(1) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 521. Longest Uncommon Subsequence I is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 521. Longest Uncommon Subsequence I?
- LeetCode 521. Longest Uncommon Subsequence I is rated Easy on LeetCode.
- What is the time complexity of LeetCode 521. Longest Uncommon Subsequence I?
- The Python solution on this page runs in O(n), where n is the length of the longer string among `a` and `b`.
- What is the space complexity of LeetCode 521. Longest Uncommon Subsequence I?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 521. Longest Uncommon Subsequence I cover?
- LeetCode 521. Longest Uncommon Subsequence I is tagged String on LeetCode.