15 April 2024

Medium

3. Longest Substring Without Repeating Characters

Link: https://leetcode.com/problems/longest-substring-without-repeating-characters

Description: Given a string, find the length of the longest substring without repeating characters.

Solution:

Using a sliding window approach, we can keep track of the characters in the current substring using a set. We iterate through the string and add characters to the set until we encounter a character that is already in the set. At this point, we remove characters from the start of the substring until the duplicate character is removed. We continue this process until we reach the end of the string and keep track of the maximum length of the substring. When we removing first character from the set, we starting calculating the length of the substring from the next character. This gives us the length of the longest substring without repeating characters.

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function (s) {
  const set = new Set()
  let maxLen = 0
  let start = 0
  let end = 0

  while (end < s.length) {
    if (!set.has(s[end])) {
      set.add(s[end])
      maxLen = Math.max(maxLen, end - start + 1)
      end++
    } else {
      set.delete(s[start])
      start++
    }
  }

  return maxLen
}