Finding the longest substring uncommon in array in JavaScript

In JavaScript, finding the longest uncommon subsequence in an array involves identifying the longest string that appears only once or doesn't exist as a subsequence in other strings.

Understanding Subsequence

A subsequence is a sequence derived from another sequence by deleting some characters without changing the order of remaining elements. Any string is a subsequence of itself, and an empty string is a subsequence of any string.

Problem Definition

We need to find the length of the longest uncommon subsequence among an array of strings. An uncommon subsequence is a subsequence of one string that is not a subsequence of any other string in the array. If no uncommon subsequence exists, return -1.

Key Insight

The solution relies on a crucial observation: if a string is unique (appears only once) in the array, then the string itself is an uncommon subsequence since it cannot be a subsequence of any other different string.

Example

For the input array ["aba", "cdc", "eae"], each string is unique, so each string itself is an uncommon subsequence of length 3.

const arr = ["aba", "cdc", "eae"];

const longestUncommon = (strs) => {
    // Count frequency of each string
    const freq = {};
    for (let str of strs) {
        freq[str] = (freq[str] || 0) + 1;
    }
    
    let maxLength = -1;
    
    // Find the longest string that appears only once
    for (let str of strs) {
        if (freq[str] === 1) {
            maxLength = Math.max(maxLength, str.length);
        }
    }
    
    return maxLength;
};

console.log(longestUncommon(arr));
3

Alternative Test Cases

// Test case 1: All strings are the same
console.log(longestUncommon(["aaa", "aaa", "aa"])); // -1

// Test case 2: Mixed unique and duplicate strings
console.log(longestUncommon(["aaa", "aaa", "aa", "bb"])); // 3

// Test case 3: Single string
console.log(longestUncommon(["hello"])); // 5
-1
3
5

How It Works

The algorithm works in two steps:

  1. Count Frequencies: Create a frequency map to count occurrences of each string
  2. Find Maximum: Among strings that appear exactly once, find the one with maximum length

If no string appears exactly once, return -1 since no uncommon subsequence exists.

Time Complexity

The solution has O(n) time complexity where n is the number of strings, making it efficient for large arrays.

Conclusion

The longest uncommon subsequence problem has an elegant solution: any unique string in the array is itself an uncommon subsequence. Simply find the longest string that appears exactly once in the array.

Updated on: 2026-03-15T23:19:00+05:30

247 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements