0

I created a solution to a Leetcode problem.

I am supposed to find the longest substring's length in a string without repeating characters.

Below is my code:

let lengthOfLongestSubstring = (s) => {
    let result = [];
    for (let i = 0; i < s.length; i++) {
        result.push([]);
        let n = i;
        while (s[n] && !result[i].includes(s[n])) {
            result[i].push(s[n]);
            n++;
        }
        result[i] = result[i].length;
    }
    return Math.max(...result);
}

console.log(lengthOfLongestSubstring("abcabcbb")); // should get output 3 because of "abc"
console.log(lengthOfLongestSubstring("bbbbb")); // should get output 1 because of "b"
console.log(lengthOfLongestSubstring("pwwkew")); // should get output 3 because of "wke"

When I try to submit it, I get the below error message: Error message

What is the reason for this?

PS: You are not allowed to change the name of the function.

iamaprogrammer
  • 115
  • 3
  • 10
  • 2
    Hint: What does `Math.max(...[])` give you? Is that what LC wants? How could you detect this situation and return the value they expect for this edge case? – ggorlen Apr 19 '22 at 13:51
  • @ggorlen I added the desired output in the question just now. I get the correct output when I run it but get an error message when I try to submit it. – iamaprogrammer Apr 19 '22 at 14:00
  • When the input is empty it gives you -Infinity instead of zero. – James Apr 19 '22 at 14:17
  • Did you read the duplicate. It will answer your question. – JΛYDΞV Apr 21 '22 at 06:36

0 Answers0