Approach
Sorting and greedy selection
For Longest Uncommon Subsequence II, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 36 lines of Java from the credited upstream file 522.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 4 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int findLUSlength(String[] strs) {3 Set<String> seen = new HashSet<>();4 Set<String> duplicates = new HashSet<>();5 6 for (final String str : strs)7 if (seen.contains(str))8 duplicates.add(str);9 else10 seen.add(str);11 12 Arrays.sort(strs, (a, b) -> b.length() - a.length());13 14 for (int i = 0; i < strs.length; ++i) {15 if (duplicates.contains(strs[i]))16 continue;17 boolean isASubsequence = false;18 for (int j = 0; j < i; ++j)19 isASubsequence |= isSubsequence(strs[i], strs[j]);20 if (!isASubsequence)21 return strs[i].length();22 }23 24 return -1;25 }26 27 28 private boolean isSubsequence(final String a, final String b) {29 int i = 0;30 for (final char c : b.toCharArray())31 if (i < a.length() && c == a.charAt(i))32 ++i;33 return i == a.length();34 }35}36