Implement the longestSubstringWithoutRepeat method that returns the length of the longest substring that has no repeated characters.

The input contains a string text. Your task is to return the length of the longest contiguous substring that does not contain repeated characters.

A substring must use consecutive characters from the original string. For example, in abcabcbb, the longest substring without repeating characters is abc, so the answer is 3.

Example 1

Input
text (string) = abcabcbb
Returns (int) 3

Example 2

Input
text (string) = bbbbb
Returns (int) 1

Example 3

Input
text (string) = pwwkew
Returns (int) 3

Use a sliding window where the current window always contains unique characters.

Move the right pointer through the string. If the current character was already seen inside the current window, move the left pointer after its previous position. Update the best length after each step.

Pseudocode:

function longestSubstringWithoutRepeat(text):
    left = 0
    best = 0
    lastSeen = empty map
    for right from 0 to length(text) - 1:
        current = text[right]
        if current exists in lastSeen and lastSeen[current] >= left:
            left = lastSeen[current] + 1
        lastSeen[current] = right
        best = max(best, right - left + 1)
    return best
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.