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 Problema = "aba"b = "cdc"Are they different? "aba" ≠ "cdc" ✓Uncommon Subsequences:"aba" is subsequence of a but not b"cdc" is subsequence of b but not aAnswer: max(len("aba"), len("cdc")) = 3If strings were identical → return -1
Understanding the Visualization
1
Input
Two strings a and b
2
Analysis
Check if strings are different
3
Output
Length of longest uncommon subsequence
Key Takeaway
🎯 Key Insight: Different strings are automatically uncommon subsequences of each other
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