Longest Uncommon Subsequence I solution and explanation
9 more videos on this problem
521. Longest Uncommon Subsequence I (Leetcode Easy)Programming Live with Larry · 5:38 · 3K views
Longest Uncommon Subsequence I | Leetcode 521 | Amazon Google Facebook interview questionSuper Lazy Coder · 7:36 · 1K views
LeetCode | Longest Uncommon Subsequence I | 521 | FAANG | Interview Preparation60 seconds of Code · 8:42 · 689 views
#6 leetcode 521. Longest Uncommon Subsequence I9527 focus · 2:01 · 478 views
521. Longest Uncommon Subsequence I || LEETCODE SOLUTION || IN C++ || DATA STRUCTURE AND ALGORITHMAbhishweta Gupta · 1:20 · 413 views
521. Longest Uncommon Subsequence I | LEETCODE EASYcode Explainer · 4:29 · 301 views
521 Longest Uncommon Subsequence I | Leetcode | PythonAbdullah Arshed · 3:19 · 243 views
Leetcode 521: Longest Uncommon Subsequence IYouScaredMe · 3:10 · 206 views
Leetcode solving :521. Longest Uncommon Subsequence IMath Geeks · 2:23 · 165 views
521. Longest Uncommon Subsequence I with python | Leetcode with Python | Best ExplanationArsalan Ahmed · 2:52 · 92 views
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.
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 <= 100aandbconsist of lower-case English letters.
Approach overview
Problem Overview: Given two strings a and b, return the length of the longest string that is a subsequence of one string but not the other. If both strings are identical, no such subsequence exists and the answer is -1.
Approach 1: Subsequence Verification (O(n + m) time, O(1) space)
The direct interpretation is to verify whether one string is a subsequence of the other. Use a two‑pointer scan: iterate through the larger string while advancing a pointer on the candidate subsequence when characters match. Perform this check twice—once to see if a is a subsequence of b and once for the reverse. If a is not a subsequence of b, then the entire string a itself becomes an uncommon subsequence. The same logic applies to b. This approach demonstrates understanding of subsequence matching using two pointers and basic string traversal.
Approach 2: Direct String Comparison (O(n) time, O(1) space)
The key observation simplifies the problem drastically. If the two strings are exactly equal, every subsequence of one will also appear in the other, so the answer must be -1. If they differ, the longer string itself cannot be a subsequence of the shorter one, which means the entire longer string is the longest uncommon subsequence. You only need a single equality check and a length comparison. This turns what initially looks like a subsequence problem into a simple comparison on string lengths.
Recommended for interviews: Interviewers expect the direct comparison insight. Many candidates initially attempt subsequence checks with two pointers, which works but adds unnecessary logic. Recognizing that identical strings are the only failing case leads to the optimal O(n) solution with constant space. Showing the subsequence verification approach first can demonstrate reasoning, but the direct comparison method shows strong problem‑solving intuition.
Approach 1: Direct String Comparison
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.
- If
ais equal tob, return -1 because all subsequences ofaare subsequences ofband vice versa. - If
ais not equal tob, return the maximum length ofaorbsince the longer string itself cannot be a subsequence of the other.
def findLUSlength(a: str, b: str) -> int:
return -1 if a == b else max(len(a), len(b))
print(findLUSlength("aba", "cdc"))public class Main {
public static int findLUSlength(String a, String b) {
return a.equals(b) ? -1 : Math.max(a.length(), b.length());
}
public static void main(String[] args) {
String a = "aba";
String b = "cdc";
System.out.println(findLUSlength(a, b));
}
}#include <iostream>
#include <string>
int findLUSlength(std::string a, std::string b) {
return a == b ? -1 : std::max(a.size(), b.size());
}
int main() {
std::string a = "aba";
std::string b = "cdc";
std::cout << findLUSlength(a, b) << std::endl;
return 0;
}function findLUSlength(a, b) {
return a === b ? -1 : Math.max(a.length, b.length);
}
console.log(findLUSlength("aba", "cdc"));#include <stdio.h>
#include <string.h>
int findLUSlength(char * a, char * b) {
return strcmp(a, b) == 0 ? -1 : (strlen(a) > strlen(b) ? strlen(a) : strlen(b));
}
int main() {
char a[] = "aba";
char b[] = "cdc";
printf("%d\n", findLUSlength(a, b));
return 0;
}using System;
class Program {
public static int FindLUSlength(string a, string b) {
return a == b ? -1 : Math.Max(a.Length, b.Length);
}
static void Main() {
string a = "aba";
string b = "cdc";
Console.WriteLine(FindLUSlength(a, b));
}
}This Python solution uses simple comparison to check strings for equality. The max function determines the longest string for different inputs.
Time Complexity: O(n) for string comparison.
Space Complexity: O(1), no extra space is required.
Approach 2: Substring Verification
Another approach is to analyze the problem by considering the entire strings as potential subsequences and determine their existence in the other string.
- Check if one string is a subsequence of the other and vice versa.
- If neither string is a subsequence of the other, return the length of the longest string.
- If one is a subsequence of the other, then no uncommon subsequence exists, return -1.
def is_subsequence(s, t):
it = iter(t)
return all(c in it for c in s)
def findLUSlength(a: str, b: str) -> int:
if is_subsequence(a, b) or is_subsequence(b, a):
return -1
return max(len(a), len(b))
print(findLUSlength("aba", "cdc"))public class Main {
public static boolean isSubsequence(String s, String t) {
int i = 0, j = 0;
while (i < s.length() && j < t.length()) {
if (s.charAt(i) == t.charAt(j)) i++;
j++;
}
return i == s.length();
}
public static int findLUSlength(String a, String b) {
if (isSubsequence(a, b) || isSubsequence(b, a)) return -1;
return Math.max(a.length(), b.length());
}
public static void main(String[] args) {
String a = "aba";
String b = "cdc";
System.out.println(findLUSlength(a, b));
}
}#include <iostream>
#include <string>
bool isSubsequence(std::string s, std::string t) {
int i = 0, j = 0;
while (i < s.size() && j < t.size()) {
if (s[i] == t[j]) i++;
j++;
}
return i == s.size();
}
int findLUSlength(std::string a, std::string b) {
if (isSubsequence(a, b) || isSubsequence(b, a)) return -1;
return std::max(a.size(), b.size());
}
int main() {
std::string a = "aba";
std::string b = "cdc";
std::cout << findLUSlength(a, b) << std::endl;
return 0;
}function isSubsequence(s, t) {
let i = 0, j = 0;
while (i < s.length && j < t.length) {
if (s[i] === t[j]) i++;
j++;
}
return i === s.length;
}
function findLUSlength(a, b) {
if (isSubsequence(a, b) || isSubsequence(b, a)) return -1;
return Math.max(a.length, b.length);
}
console.log(findLUSlength("aba", "cdc"));#include <stdio.h>
#include <string.h>
int isSubsequence(char *s, char *t) {
int i = 0, j = 0;
while (i < strlen(s) && j < strlen(t)) {
if (s[i] == t[j]) i++;
j++;
}
return i == strlen(s);
}
int findLUSlength(char *a, char *b) {
if (isSubsequence(a, b) || isSubsequence(b, a)) return -1;
return strlen(a) > strlen(b) ? strlen(a) : strlen(b);
}
int main() {
char a[] = "aba";
char b[] = "cdc";
printf("%d\n", findLUSlength(a, b));
return 0;
}using System;
class Program {
public static bool IsSubsequence(string s, string t) {
int i = 0, j = 0;
while (i < s.Length && j < t.Length) {
if (s[i] == t[j]) i++;
j++;
}
return i == s.Length;
}
public static int FindLUSlength(string a, string b) {
if (IsSubsequence(a, b) || IsSubsequence(b, a)) return -1;
return Math.Max(a.Length, b.Length);
}
static void Main() {
string a = "aba";
string b = "cdc";
Console.WriteLine(FindLUSlength(a, b));
}
}The Python solution leverages a function is_subsequence using iterators to detect subsequences. It applies this for both a and b, then returns appropriately.
Time Complexity: O(n + m) as the strings are processed.
Space Complexity: O(1), since generator expressions create no persistent data structures.
Approach 3: Quick Thinking
If strings a and b are equal, then they have no special sequences, return -1; otherwise, return the length of the longer string.
The time complexity is O(n), where n is the length of the longer string among a and b. The space complexity is O(1).
function findLUSlength(a: string, b: string): number {
return a === b ? -1 : Math.max(a.length, b.length);
}func findLUSlength(a string, b string) int {
if a == b {
return -1
}
if len(a) > len(b) {
return len(a)
}
return len(b)
}impl Solution {
pub fn find_lu_slength(a: String, b: String) -> i32 {
if a == b {
return -1;
}
a.len().max(b.len()) as i32
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Direct String Comparison | Time Complexity: O(n) for string comparison. |
| Substring Verification | Time Complexity: O(n + m) as the strings are processed. |
| Quick Thinking | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Subsequence Verification (Two Pointers) | O(n + m) | O(1) | When solving the problem directly by checking subsequence relationships between both strings |
| Direct String Comparison | O(n) | O(1) | Best approach once you realize identical strings are the only case where no uncommon subsequence exists |
Frequently asked questions
Is Longest Uncommon Subsequence I easy or hard?
LeetCode classifies this problem as Easy. The challenge comes from recognizing the key observation that identical strings eliminate all uncommon subsequences. Once that insight is clear, the implementation becomes a simple comparison.
Longest Uncommon Subsequence I Python/Java solution
In Python or Java, check if the two strings are equal. If they are equal, return -1. Otherwise return max(len(a), len(b)) in Python or Math.max(a.length(), b.length()) in Java. This concise logic implements the optimal O(n) solution.
How to solve Longest Uncommon Subsequence I in O(n)?
Compare the two input strings directly. If they are identical, return -1 because every subsequence will match in both strings. If they differ, return the maximum of their lengths since the longer string itself cannot be a subsequence of the shorter one. This solution scans the strings once, giving O(n) time complexity.
What is the best approach for Longest Uncommon Subsequence I?
Direct string comparison is the optimal approach. If the two strings are equal, return -1 because every subsequence appears in both. Otherwise, the longer string itself is the longest uncommon subsequence. This runs in O(n) time with O(1) space.
Is Longest Uncommon Subsequence I asked at Google/Amazon/Meta?
Variants of subsequence and string comparison problems frequently appear in interviews at companies like Amazon, Google, and Meta. While this exact question is easier than typical interview problems, it tests understanding of subsequences and recognizing hidden simplifications.
What data structure is used in Longest Uncommon Subsequence I?
The problem mainly uses basic string operations. Some implementations demonstrate subsequence checks using the two-pointer technique on strings, but the optimal solution only requires direct string comparison and length evaluation.
What is the time complexity of Longest Uncommon Subsequence I?
The optimal solution runs in O(n) time where n is the length of the longer string, because it only requires a string equality check and length comparison. Space complexity is O(1) since no additional data structures are required.
