Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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:
- Concatenate: Combine both input strings
- Normalize: Convert to lowercase for consistency
- Remove duplicates: Use Set or manual checking
- Sort: Arrange characters alphabetically
- 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.
Advertisements
