- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Longest possible string built from two strings in JavaScript
Problem
We are required to write a JavaScript function that takes in two strings s1 and s2 including only letters from ato z.
Our function should return a new sorted string, the longest possible, containing distinct letters - each taken only once - coming from s1 or s2.
Example
Following is the code −
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));
Output
Following is the console output −
abcdefklmopqwxy
Advertisements