algoadvance

Leetcode 522. Longest Uncommon Subsequence II

Problem Statement

Given a list of strings, you need to find the longest string that is an uncommon subsequence among the given strings. An uncommon subsequence is a string that is a subsequence of one string but not of any other string. If no such string exists, return -1.

A subsequence is a sequence derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Clarifying Questions

Code

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

bool isSubsequence(const string& a, const string& b) {
    int n = a.size(), m = b.size();
    int i = 0, j = 0;
    while (i < n && j < m) {
        if (a[i] == b[j]) {
            i++;
        }
        j++;
    }
    return i == n;
}

int findLUSlength(vector<string>& strs) {
    sort(strs.begin(), strs.end(), [](const string& a, const string& b) {
        return a.size() > b.size();
    });

    for (int i = 0; i < strs.size(); ++i) {
        bool isUncommon = true;
        for (int j = 0; j < strs.size(); ++j) {
            if (i != j && isSubsequence(strs[i], strs[j])) {
                isUncommon = false;
                break;
            }
        }
        if (isUncommon) {
            return strs[i].size();
        }
    }
    return -1;
}

int main() {
    vector<string> strs = {"aba", "cdc", "eae"};
    cout << findLUSlength(strs) << endl;
    return 0;
}

Strategy

  1. Sorting: Sort the strings by length in descending order. This allows us to check longer strings first, which could potentially be our answer due to their length.
  2. Subsequence Checking: For each string, check if it is a subsequence of any other string longer or equal in length.
  3. IsUncommon Calculation: If a string is not a subsequence of any other string, it is an uncommon subsequence.
  4. Early Return: Return the length of the first uncommon subsequence found during iteration.
  5. Edge Handling: If no such uncommon subsequence exists among the input strings, return -1.

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI