Longest Uncommon Subsequence II - Problem

Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1.

An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others.

A subsequence of a string s is a string that can be obtained after deleting any number of characters from s. For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", "aeb", and "" (empty string).

Input & Output

Example 1 — Mixed Unique and Duplicate
$ Input: strs = ["aba", "cdc", "eae", "eae"]
Output: 3
💡 Note: "aba" and "cdc" are unique strings (appear only once). "eae" appears twice so it's not uncommon. The longest unique strings have length 3.
Example 2 — All Identical Strings
$ Input: strs = ["aaa", "aaa", "aa"]
Output: 2
💡 Note: "aaa" appears twice, but "aa" is unique. The longest uncommon subsequence has length 2.
Example 3 — All Strings Are Identical
$ Input: strs = ["abc", "abc", "abc"]
Output: -1
💡 Note: All strings are identical, so no string is unique. No uncommon subsequence exists.

Constraints

  • 2 ≤ strs.length ≤ 50
  • 1 ≤ strs[i].length ≤ 10
  • strs[i] consists of lowercase English letters

Visualization

Tap to expand
Longest Uncommon Subsequence IIFind the longest string that appears only once"aba"Count: 1 ✓"cdc"Count: 1 ✓"eae"Count: 2 ✗"eae"Count: 2 ✗Unique strings: "aba" (length 3), "cdc" (length 3)Result: 3Any unique string is an uncommon subsequence of itself
Understanding the Visualization
1
Input
Array of strings: ["aba", "cdc", "eae", "eae"]
2
Process
Find strings that appear exactly once
3
Output
Length of longest unique string: 3
Key Takeaway
🎯 Key Insight: A string that appears only once is automatically an uncommon subsequence
Asked in
Google 15 Facebook 12
28.0K Views
Medium Frequency
~15 min Avg. Time
856 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