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 II INPUT String Array: strs ["aba","cdc","eae","eae"] Visual Breakdown: "aba" "cdc" "eae" "eae" idx 0 idx 1 idx 2 idx 3 Note: "eae" appears twice (duplicates = not uncommon) ALGORITHM STEPS 1 Count Frequencies Build HashMap of string counts "aba": 1 "cdc": 1 "eae": 2 HashMap<String, Count> 2 Filter Unique Strings Skip strings with count > 1 3 Check Subsequences Verify not subseq of others "aba" subseq of "cdc"? NO "aba" subseq of "eae"? NO "cdc" subseq of "aba"? NO "cdc" subseq of "eae"? NO 4 Find Max Length Return longest valid string FINAL RESULT Uncommon Subsequences Found: "aba" len = 3 "cdc" len = 3 "eae" DUPLICATE - Skip Maximum Length: 3 OK - Both "aba" and "cdc" are valid uncommon subseq Key Insight: A string is an uncommon subsequence if: (1) It appears exactly once in the array, AND (2) It is NOT a subsequence of any other string. Use HashMap to count frequencies first, then check each unique string against others. Sort by length descending for optimization. TutorialsPoint - Longest Uncommon Subsequence II | Hash Map - Count Frequencies Approach
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