LeetCode 521: Longest Uncommon Subsequence I Solution
Master LeetCode problem 521 (Longest Uncommon Subsequence I), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
521. Longest Uncommon Subsequence I
Problem Explanation
Explanation
To solve this problem, we need to find the longest uncommon subsequence between two strings a and b. An uncommon subsequence is a subsequence of exactly one of the strings. If no such uncommon subsequence exists, we return -1.
We can observe that if the two strings a and b are different, then the longer string itself is the longest uncommon subsequence. If the strings are the same, then there is no uncommon subsequence as every subsequence of one string is also a subsequence of the other.
Therefore, we simply compare the strings. If they are the same, we return -1. Otherwise, we return the length of the longer string.
Time Complexity
The time complexity of this solution is O(max(a.length, b.length)), where a and b are the lengths of the input strings.
Space Complexity
The space complexity is O(1) as we are not using any extra space.
Solution Code
class Solution {
public int findLUSlength(String a, String b) {
if (a.equals(b)) {
return -1;
}
return Math.max(a.length(), b.length());
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 521 (Longest Uncommon Subsequence I)?
This page provides optimized solutions for LeetCode problem 521 (Longest Uncommon Subsequence I) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 521 (Longest Uncommon Subsequence I)?
The time complexity for LeetCode 521 (Longest Uncommon Subsequence I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 521 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 521 in Java, C++, or Python.