DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 53

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
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
    }
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)