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.
An uncommon subsequence between two strings is a string that is a subsequence of exactly one of them.
Example 1:
Input: a = "aba", b = "cdc" Output: 3 Explanation: One longest uncommon subsequence is "aba" because "aba" is a subsequence of "aba" but not "cdc". Note that "cdc" is also a longest uncommon subsequence.
Example 2:
Input: a = "aaa", b = "bbb" Output: 3 Explanation: The longest uncommon subsequences are "aaa" and "bbb".
Example 3:
Input: a = "aaa", b = "aaa"
Output: -1
Explanation: Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a. So the answer would be -1.
Constraints:
1 <= a.length, b.length <= 100a and b consist of lower-case English letters.This approach takes advantage of the fact that if two strings are identical, there are no uncommon subsequences. If they are different, the longest uncommon subsequence is the longest string itself.
a is equal to b, return -1 because all subsequences of a are subsequences of b and vice versa.a is not equal to b, return the maximum length of a or b since the longer string itself cannot be a subsequence of the other.This C solution uses the standard library's strcmp function to check for string equality. If the strings are equal, it returns -1. Otherwise, it uses the strlen function to find the length of the longest string and returns that as the length of the longest uncommon subsequence.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n) where n is the length of the strings, due to the string comparison.
Space Complexity: O(1), no additional space is needed.
Another approach is to analyze the problem by considering the entire strings as potential subsequences and determine their existence in the other string.
This solution defines a helper function isSubsequence that checks if one string is a subsequence of another using two pointers. It then uses this helper in findLUSlength to check the relations between a and b.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n + m) where n and m are the lengths of the strings.
Space Complexity: O(1), since no additional structures are employed.
| Approach | Complexity |
|---|---|
| Direct String Comparison | Time Complexity: O(n) where n is the length of the strings, due to the string comparison. |
| Substring Verification | Time Complexity: O(n + m) where n and m are the lengths of the strings. |
Longest Common Subsequence - Dynamic Programming - Leetcode 1143 • NeetCode • 323,891 views views
Watch 9 more video solutions →Practice Longest Uncommon Subsequence I with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor