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
- 39 lines of C++ from the credited upstream file 522.cpp.
- The implementation visibly relies on sequence storage, hash 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:3 int findLUSlength(vector<string>& strs) {4 unordered_set<string> seen;5 unordered_set<string> duplicates;6 7 for (const string& str : strs)8 if (seen.contains(str))9 duplicates.insert(str);10 else11 seen.insert(str);12 13 ranges::sort(strs, ranges::greater{},14 [](const string& s) { return s.length(); });15 16 for (int i = 0; i < strs.size(); ++i) {17 if (duplicates.contains(strs[i]))18 continue;19 bool isASubsequence = false;20 for (int j = 0; j < i; ++j)21 isASubsequence |= isSubsequence(strs[i], strs[j]);22 if (!isASubsequence)23 return strs[i].length();24 }25 26 return -1;27 }28 29 private:30 31 bool isSubsequence(const string& a, const string& b) {32 int i = 0;33 for (const char c : b)34 if (i < a.length() && c == a[i])35 ++i;36 return i == a.length();37 };38};39