Longest substring without repeating characters

Asked atAmazonMeeshoQuince
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given a string, S. Find the length of the longest substring without repeating characters.

Input : S = "abcddabac" Output : 4 Explanation : The answer is "abcd" , with a length of 4.

Input : S = "aaabbbccc" Output : 2 Explanation : The answers are "ab" , "bc". Both have maximum length 2.

Input : S = "aaaa"

  • 1 <= S.length <= 5*104
  • S contains only English lowercase letters.

cpp

class Solution{
  public:
    int longestNonRepeatingSubstring(string& s){
        //your code goes here
    }
};

java

class Solution {
    public int longestNonRepeatingSubstring(String s) {
        //your code goes here
    }
}

python

class Solution:
    def longestNonRepeatingSubstring(self, s):
        #your code goes here

javascript

class Solution {
    longestNonRepeatingSubstring(s) {
        //your code goes here
    }
}

csharp

public class Solution
{
    public int LongestNonRepeatingSubstring(string s)
    {
        //your code goes here
    }
}

go

func longestNonRepeatingSubstring(s string) int {

}
Stuck? Show a way to structure it+
  1. 01Keep a left boundary and the latest index for each character.
  2. 02Extend the right boundary one character at a time.
  3. 03When a repeated character is inside the window, move left past its earlier index.
  4. 04Update the best window length after restoring uniqueness.

Reference answer

Then expect these follow-ups

  • How would you return the substring rather than its length?

    Tests: window reconstruction

  • How does the approach change for Unicode grapheme clusters?

    Tests: string representation

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question