This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan
The task is to implement a function to find the longest substring that has no repeated characters.
The boilerplate code:
function longestUniqueSubstr(str) {
// your code here
}
Keep a moving window[start, end] that contains unique characters.
let start = 0;
let maxLen = 0;
let maxSubstr = "";
const seen = new Map(); // stores the last index of each character
Check through the window, if there's a duplicate character in that window, move the start to after the previous index of that character
for (let end = 0; end < str.length; end++) {
const char = str[end];
if (seen.has(char) && seen.get(char) >= start) {
start = seen.get(char) + 1;
}
seen.set(char, end);
}
If there's a longer substring, it is updated alongside the maximum length
const currentLen = end - start + 1;
if (currentLen > maxLen) {
maxLen = currentLen;
maxSubstr = str.slice(start, end + 1);
}
The final code
function longestUniqueSubstr(str) {
// your code here
let start = 0;
let maxLen = 0;
let maxSubStr =''
const seen = new Map()
for(let end = 0; end < str.length; end++) {
const char = str[end]
if(seen.has(char) && seen.get(char) >= start) {
start = seen.get(char) + 1;
}
seen.set(char, end)
const currentLen = end - start + 1;
if(currentLen > maxLen) {
maxLen = currentLen;
maxSubStr = str.slice(start, end + 1)
}
}
return maxSubStr;
}
That's all folks!
This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan
Bukunmi Odugbesan | Sciencx (2025-11-12T14:44:58+00:00) Coding Challenge Practice – Question 53. Retrieved from https://www.scien.cx/2025/11/12/coding-challenge-practice-question-53/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.