findLongestSubString

Write a function called findLongestSubstring, which accepts a string and returns the length of the longest substring with all distinct characters.

I don’t understand how the use-cases answers come to be?

findLongestSubString("thisisawesome") // 6 (my answer is 5 because "isawe" is longest), the rest of use cases im baffled as well.
findLongestSubString("thecatinthehat") // 7
findLongestSubString("longestsubstring") // 8
findLongestSubString("thisishowwedoit") // 6

The substring doesn’t have to start at the beginning, so you have lots of options to check.

For the first string, ‘awesom’.

1 Like

Hi again. So I have solved this algorithm myself thanks to u. But I’ve found another solution from someone else:

function findLongestSubstring(str) {
  let longest = 0;
  let seen = {};
  let start = 0;
 
  for (let i = 0; i < str.length; i++) {
    let char = str[i];
    if (seen[char]) {
      start = Math.max(start, seen[char]);
    }
    // index - beginning of substring + 1 (to include current in count)
    longest = Math.max(longest, i - start + 1);
    // store the index of the next char so as to not double count
    seen[char] = i + 1;
  }
  return longest;
}

findLongestSubstring("thecatinthehat"); // 7

I do not understand this algorithm at all and how the answer comes out perfectly. Can you assist me to understand this?