
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find Longest Substring with At Least N Repeating Characters in JavaScript
We are required to write a JavaScript function that takes in a string as the first argument and a positive integer n as the second argument.
The string is likely to contain some repeating characters. The function should find out and return the length of the longest substring from the original string in which all characters appear at least n number of times.
For example −
If the input string and the number are −
const str = 'kdkddj'; const num = 2;
Then the output should be −
const output = 5;
because the desired longest substring is 'kdkdd'
Example
Following is the code −
const str = 'kdkddj'; const num = 2; const longestSubstring = (str = '', num) => { if(str.length < num){ return 0 }; const map = {} for(let char of str) { if(char in map){ map[char] += 1; }else{ map[char] = 1; } } const minChar = Object.keys(map).reduce((minKey, key) => map[key] < map[minKey] ? key : minKey) if(map[minChar] >= num){ return str.length; }; substrings = str.split(minChar).filter((subs) => subs.length >= num); if(substrings.length == 0){ return 0; }; let max = 0; for(ss of substrings) { max = Math.max(max, longestSubstring(ss, num)) }; return max; }; console.log(longestSubstring(str, num));
Output
Following is the console output −
5
Advertisements