Instagram
youtube
Facebook
Twitter

Longest Substring Without Repeating Characters Leetcode Solution

In this tutorial, we are going to find length of the longest substring without repeating characters

Problem statement

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

Example 1:

Input: s = "abcabcbb"
Output: 3

Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"
Output: 1

Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"
Output: 3

Explanation: The answer is "wke", with a length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols, and spaces.

 

Solution

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        dct = {} #initiate a empty dictionary
        start, max_ = 0, 0 #make 2 variables which will store the starting index and max length of longest substring

        #loop through the string

        for i in range(len(s)): 

            #check if the current character already exist in the dictionary
            if s[i] in dct:
                
                #if it exists then assign your start variable the maximum value between start and character index in the dictionary + 1

                start = max(start, dct[s[i]]+1)

            #assign max_ to max of itself and i-start+1
            max_ = max(max_, i-start+1)

            #add the character to the dictionary if it doesn't exist
            dct[s[i]] = i
        
            #return max length of the substring
            return max_