Similar Problems
Similar Problems not available
Longest Uncommon Subsequence I - Leetcode Solution
Companies:
LeetCode: Longest Uncommon Subsequence I Leetcode Solution
Difficulty: Easy
Topics: string
Problem Statement:
Given two strings a and b, find the length of the longest uncommon subsequence between them.
A subsequence of a string s is a string that can be obtained by deleting any number of characters from s. For example, "abcde" is a subsequence of "adebc" because you can delete the characters "d" and "e" from "adebc" to get "abcde". Other subsequences of "adebc" include "a", "b", "c", "d", "e", "ad", "ae", "ab", "ac", "de", "dc", and so on.
A subsequence is called uncommon if it does not appear in both strings a and b. For example, if a = "abcde" and b = "bcefg", then "abcde" and "bcefg" do not have any common subsequences, so the answer is 5 (the length of the longest uncommon subsequence).
Solution:
The approach we can take for this problem is very simple. We check for the lengths of the two strings a and b.
If the lengths of a and b are different, then the longer string is the longest uncommon subsequence.
If the lengths of a and b are the same, we need to check if the two strings are the same or not. If they are not the same, then the longest uncommon subsequence is the whole string (as the two strings do not have any common subsequences), otherwise there is no uncommon subsequence.
Let's look at the implementation:
class Solution: def findLUSlength(self, a: str, b: str) -> int: if a == b: return -1 else: return max(len(a), len(b))
In this code, we first check for the case where the two strings are the same. If they are the same, then there is no uncommon subsequence, so we return -1.
If they are not the same, then we return the length of the longer string since any subsequence that is longer than the shorter string will be uncommon.
This method is very intuitive and simple to understand. The time complexity of this approach is O(1), since we are just comparing the lengths of the strings and returning the maximum length.
Longest Uncommon Subsequence I Solution Code
1