Longest Uncommon Subsequence II - Problem

You are given an array of strings and need to find the longest uncommon subsequence among them. An uncommon subsequence is a string that is a subsequence of exactly one string in the array, but not a subsequence of any other string.

A subsequence is formed by deleting some (possibly zero) characters from a string while maintaining the relative order of remaining characters. For example, "abc" is a subsequence of "aebdc" by removing characters at positions 1 and 3.

Goal: Return the length of the longest uncommon subsequence. If no uncommon subsequence exists, return -1.

Key Insight: Any string that appears only once in the array is automatically an uncommon subsequence (since it's a subsequence of itself but not of any other string)!

Input & Output

example_1.py โ€” Basic Case
$ Input: ["aba", "cdc", "eae"]
โ€บ Output: 3
๐Ÿ’ก Note: All three strings are unique (appear once), and none can be formed as a subsequence of another. The longest length is 3.
example_2.py โ€” With Duplicates
$ Input: ["aaa", "aaa", "aa"]
โ€บ Output: 2
๐Ÿ’ก Note: "aaa" appears twice, so it's not uncommon. "aa" appears once and is not a subsequence of any other distinct string, so return 2.
example_3.py โ€” All Same Strings
$ Input: ["aaa", "aaa", "aaa"]
โ€บ Output: -1
๐Ÿ’ก Note: All strings are identical, so no uncommon subsequence exists.

Constraints

  • 2 โ‰ค strs.length โ‰ค 50
  • 1 โ‰ค strs[i].length โ‰ค 10
  • strs[i] consists of lowercase English letters only

Visualization

Tap to expand
๐Ÿ’ก The Key Insight VisualizationWhy unique strings are automatically uncommon:If string S appears exactly once:โ€ข S is a subsequence of itself โœ“โ€ข S cannot be a subsequence of any different string โœ“"aba"appearsonceUnique!"cdc"appearsonceUnique!"abc"appearstwiceNot unique๐ŸŽฏ Algorithm Steps1. Count frequency of each string2. Find strings with frequency = 13. Return length of longest unique string
Understanding the Visualization
1
Collect All Signatures
Count how many times each string pattern appears
2
Find Unique Patterns
Identify strings that appear exactly once
3
Pick the Longest
Return the length of the longest unique string
Key Takeaway
๐ŸŽฏ Key Insight: A string appearing exactly once is guaranteed to be uncommon - no complex subsequence checking needed!
Asked in
Google 23 Amazon 18 Microsoft 15 Meta 12
31.2K Views
Medium Frequency
~12 min Avg. Time
892 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