Longest possible string built from two strings in JavaScript

We need to write a JavaScript function that takes two strings containing only letters from a to z and returns the longest possible sorted string with distinct letters from both strings combined.

Problem Statement

Given two strings s1 and s2, create a function that:

  • Combines both strings
  • Removes duplicate characters
  • Returns a sorted string containing each unique letter only once

Solution Using Array Methods

Here's an implementation that combines the strings, removes duplicates, and sorts the result:

const str1 = "xyaabbbccccdefww";
const str2 = "xxxxyyyyabklmopq";

const longestPossible = (str1 = '', str2 = '') => {
    const combined = str1.concat(str2);
    const lower = combined.toLowerCase();
    const split = lower.split('');
    const sorted = split.sort();
    const res = [];
    
    for (const el of sorted) {
        if (!res.includes(el)) {
            res.push(el);
        }
    }
    
    return res.join('');
};

console.log(longestPossible(str1, str2));
abcdefklmopqwxy

Optimized Solution Using Set

A more efficient approach using Set to automatically handle duplicates:

const str1 = "xyaabbbccccdefww";
const str2 = "xxxxyyyyabklmopq";

const longestPossibleOptimized = (str1 = '', str2 = '') => {
    const combined = str1.concat(str2).toLowerCase();
    const uniqueChars = [...new Set(combined)];
    return uniqueChars.sort().join('');
};

console.log(longestPossibleOptimized(str1, str2));
abcdefklmopqwxy

How It Works

The algorithm follows these steps:

  1. Concatenate: Combine both input strings
  2. Normalize: Convert to lowercase for consistency
  3. Remove duplicates: Use Set or manual checking
  4. Sort: Arrange characters alphabetically
  5. Join: Convert back to string format

Performance Comparison

Approach Time Complexity Space Complexity Readability
Array + includes() O(n²) O(n) Good
Set + spread O(n log n) O(n) Excellent

Additional Example

// Testing with different inputs
console.log(longestPossibleOptimized("aretheyhere", "yestheyarehere"));
console.log(longestPossibleOptimized("loopingisfunbutdangerous", "lessdangerousthancoding"));
aehrsty
abcdefghilmnorstuy

Conclusion

The Set-based approach provides the most efficient and readable solution for creating the longest possible string from two input strings. It automatically handles duplicates and maintains the required alphabetical sorting.

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

562 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements