Longest Uncommon Subsequence I - 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.

Input & Output

Example 1 — Different Strings
$ Input: a = "aba", b = "cdc"
Output: 3
💡 Note: Since "aba" ≠ "cdc", each string is a subsequence of itself but not the other. The longest uncommon subsequence is the entire string "aba" or "cdc", both with length 3.
Example 2 — Identical Strings
$ Input: a = "aaa", b = "aaa"
Output: -1
💡 Note: Since both strings are identical, any subsequence of one will also be a subsequence of the other. No uncommon subsequence exists.
Example 3 — Different Lengths
$ Input: a = "abc", b = "defgh"
Output: 5
💡 Note: The strings are different, so each is uncommon to the other. The longer string "defgh" has length 5, which is the answer.

Constraints

  • 1 ≤ a.length, b.length ≤ 100
  • a and b consist of lower-case English letters.

Visualization

Tap to expand
Longest Uncommon Subsequence I INPUT String a: a b a 0 1 2 String b: c d c 0 1 2 Input Values: a = "aba" b = "cdc" ALGORITHM STEPS 1 Compare Lengths len(a)=3, len(b)=3 Both are equal length 2 Check if Equal "aba" == "cdc" ? NO - strings differ! 3 Analyze Logic If a != b, then a is NOT subsequence of b (and vice versa) 4 Return Result Return max(len(a), len(b)) = max(3, 3) = 3 if a == b: return -1 else: return max(len) --> return 3 FINAL RESULT Longest Uncommon Subsequence: "aba" - unique to a "cdc" - unique to b Length of each: 3 1 2 3 OUTPUT 3 OK - Both strings are uncommon to each other Key Insight: If two strings are different, neither can be a subsequence of the other when they have equal length. The entire longer (or equal) string becomes the longest uncommon subsequence. Only return -1 when a == b. TutorialsPoint - Longest Uncommon Subsequence I | Logical Analysis - Direct Comparison
Asked in
Google 15 Amazon 8
25.0K Views
Medium Frequency
~5 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen