DEV Community

Matan Shaviro
Matan Shaviro

Posted on • Edited on

LeetCode: Longest Substring Without Repeating Characters

Let's break down the solution steps and see how each step works

We assume we received the following input:
Image description

We will create an empty set to store the letters we have encountered and a variable to keep the longest substring we have found.
Image description

Now, we will check if the value pointed to by right exists in the set. If it doesn't exist, we will add it to the set and move right one step forward. After that, we will update the longest substring by comparing the size of the set to the value stored in the longSubstr variable.
Image description

We will check if the value pointed to by right is in the set. We see that it is not, so we add it to the set and increment right by 1. After that, we take the max between the size of the set and the value in longSubstr.
Image description

We check if the value pointed to by right is in the set, meaning c is not in the set. So, we add it to the set, increment right by 1, and check the max substring.
Image description

Now, we check if the value pointed to by right, which is a, exists in the set. We see that it does, so we remove it from the set and move left one step forward.
Image description

The value pointed to by right is b, and it exists in the set.

Therefore, we move the left pointer one step forward and remove b from the set.
Image description

Now we see that b is in the set, so we remove the value pointed to by left and move left one step forward.
Image description

The value pointed to by right is c, and it exists in the set.
Therefore, we remove it from the set and move left one step forward.
Image description

We will continue with the same technique until step 17 and will get:
Image description

Here is a JavaScript implementation

function longestSubstring(s) {
  let left = 0
  let right = 0

  let maxSubstr = 0
  let set = new Set()

  while (right < s.length) {
    const currentChar = s[right]

    if (!set.has(currentChar)) {
      set.add(currentChar)
      right++
      maxSubstr = Math.max(maxSubstr, right - left) // Update max substring length
    } else {
      set.delete(s[left])
      left++
    }
  }

  return maxSubstr
}

let inputString = 'abcabcbb'
console.log(longestSubstring(inputString)) // Output: 3 ("abc")

Enter fullscreen mode Exit fullscreen mode

Top comments (0)