The function should return the length of the maximum substring in which there are no duplicate characters, but the program runs for an infinite amount of time
function findMaxLength(str) {
let right = 0;
let left = 0;
let answer = 0;
let arr = [];
while (right < str.length) {
let ch = str.split("")[right];
if (!arr.includes(ch)) {
arr.push(ch);
answer = Math.max(answer, (right - left + 1));
right++;
} else {
while (arr.includes(ch)) {
arr.splice(left, 1);
left++;
}
}
}
return answer;
}
2
Answers
The issue is the use of
arr.includes(ch)
inside the while loop. You are removing elements fromarr
usingarr.splice(left, 1)
inside the loop, therefore the conditionarr.includes(ch)
might not evaluate correctly.As an alternative, are you familiar with the lcs algorithm? It might suit your use case if we modify it slightly:
Note that the
paths
array in the algorithm isn’t needed for your use case, I simply lifted the code from here