Knowee
Questions
Features
Study Tools

Longest Substring Without Repeating CharactersGiven a string s find the length of the longest  substring without repeating characters.

Question

Longest Substring Without Repeating Characters

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

🧐 Not the exact question you are looking for?Go ask a question

Solution

This problem can be solved using the sliding window technique. Here are the steps in Python:

  1. Initialize two pointers, start and end, to point to the beginning of the string. These pointers will define our current substring.

  2. Initialize a dictionary, used_chars, to keep track of the characters we have seen and their latest positions.

  3. While end is less than the length of the string, do the following:

    • If the character at end is not in used_chars, add it to used_chars and increment end.

    • If the character at end is in used_chars, move start to the right of the previous instance of the character at end and update its position in used_chars.

  4. The length of the longest substring without repeating characters is the maximum length of the substring we have seen during this process.

Here is the Python code for the above steps:

def lengthOfLongestSubstring(s):
    start = max_length = 0
    used_chars = {}

    for i, char in enumerate(s):
        if char in used_chars and start <= used_chars[char]:
            start = used_chars[char] + 1
        else:
            max_length = max(max_length, i - start + 1)

        used_chars[char] = i

    return max_length

This function works by keeping track of the longest substring seen so far and the start of the current substring. When it sees a repeating character, it moves the start of the current substring to the right of the previous instance of the repeating character and updates the position of the repeating character. The length of the longest substring is updated whenever a longer substring is found.

This problem has been solved

Similar Questions

Given a string consisting of opening and closing parenthesis (let moonparenthesis only), find the length of the longest valid parenthesis sub-string

Length of the longest wordWrite a Python program to read a list of words and return the length of the longest word present within the list elements

Write a Java program to check whether a substring(abc) appears before a period(.) within a given string

Given a string A and two integer B and C.Find and return the substring of A starting from index B and ending with index C.

The library function used to find the last occurrence of a character in a string is

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.