Problem Description
Given two strings a and b, return the length of the longest uncommon subsequence between them. An uncommon subsequence is a subsequence that is a subsequence of one string but not of the other. If no such uncommon subsequence exists, return -1.
Key Insights
- If both strings are identical, every subsequence of one string is also a subsequence of the other, so the answer is -1.
- If the strings are different, the longest string itself is an uncommon subsequence.
- Therefore, when the strings are not equal, the result is the length of the longer string.
Space and Time Complexity
Time Complexity: O(1)
Space Complexity: O(1)
Solution
The solution directly compares the two strings. If they are exactly the same, every subsequence is common, so return -1. Otherwise, the longest uncommon subsequence is the entire string which has the maximum length among the two. This leads to a simple and efficient constant time solution.