

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 string with two distinct characters in JavaScript
We are required to write a JavaScript function that takes in a string as the first argument and a number (smaller than the length of string) as the second argument. The function should delete characters from the original string and prepare a new string such that it's the longest string containing at most two distinct characters.
Then at last the function should return the length of that desired string.
For example: If the input string is −
const str = 'kjeljsdl';
Then the output should be −
const output = 4;
because the longest substring with at most 2 distinct characters is 'jljl'
Example
The code for this will be −
const str = 'kjeljsdl'; const longestSubstring = (str = '') => { const { length } = str; if (length <= 1){ return 0; }; const keys = [...new Set(str)]; const arr = []; let max = 0; for (let i = 0; i < keys.length - 1; i++) { for (let j = i + 1; j < keys.length; j++) { arr.push(keys[i] + keys[j]); } } arr.forEach(item => { let sub = ''; for (let i = 0; i < str.length; i++) { if (sub[sub.length - 1] === str[i]) { sub = ''; break; } if (item.includes(str[i])) { sub += str[i]; } } if (sub && sub.length > max){ max = sub.length; }; }); return max; } console.log(longestSubstring(str));
Output
And the output in the console will be −
4
- Related Questions & Answers
- Longest Substring with At Most Two Distinct Characters in C++
- Longest Substring with At Most K Distinct Characters in C++
- Finding longest substring between two same characters JavaScript
- Longest possible string built from two strings in JavaScript
- Finding the longest Substring with At Least n Repeating Characters in JavaScript
- Program to find length of longest substring which contains k distinct characters in Python
- Largest Substring Between Two Equal Characters in a string in JavaScript
- Find the longest substring with k unique characters in a given string in Python
- Remove characters from a string contained in another string with JavaScript?
- String replace multiple characters with an asterisk in JavaScript
- Print all distinct characters of a string in order in C++
- Length of longest string chain in JavaScript
- Python – N sized substrings with K distinct characters
- Longest Substring with At Least K Repeating Characters in C++
- Generate random string/characters in JavaScript?
Advertisements