↓Skip to main content
  1. LeetCode/

LeetCode 521: Longest Uncommon Subsequence I

·1 min· ·
LeetCode Easy String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-25

  • Submissions: Accepted (first try)

Approach
#

If a == b, every subsequence of one is a subsequence of the other, so the answer is -1. Otherwise the longer string as a whole cannot be a subsequence of the other (it is longer, or equally long but different), so the answer is max(len(a), len(b)).

My Solution
#

class Solution:
    def findLUSlength(self, a: str, b: str) -> int:
        return -1 if a == b else max(len(a), len(b))

Complexity
#

Time O(n) to compare the strings, space O(1).

Mistakes to Avoid
#

  • With equal lengths but different contents, either whole string works.

Interview Explanation
#

Identical strings have no answer, so -1; otherwise the longer string as a whole cannot be a subsequence of the other, so the answer is the longer length.

Related

LeetCode 500: Keyboard Row
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 500 note: make a set for each keyboard row and keep words whose lowercase character set is a subset of one row
LeetCode 520: Detect Capital
·1 min
LeetCode Easy String
LeetCode 520 note: only three forms are valid: all caps, all lowercase, or only the first letter capitalized
LeetCode 434: Number of Segments in a String
·1 min
LeetCode Easy String
LeetCode 434 note: split() with no argument ignores extra spaces, so the number of pieces is the answer
LeetCode 345: Reverse Vowels of a String
·1 min
LeetCode Easy Two-Pointers String
LeetCode 345 note: the same two pointers as LC 917, with the condition switched to “is a vowel” (both cases)
LeetCode 504: Base 7
·1 min
LeetCode Easy Math String
LeetCode 504 note: repeatedly take % 7 and // 7 of the absolute value, then add the sign and reverse; handle 0 separately
LeetCode 541: Reverse String II
·1 min
LeetCode Easy Two-Pointers String
LeetCode 541 note: in every block of 2k reverse the first k; when fewer than k remain reverse them all, which slicing handles automatically