Data Structures19 sections · 729 units
Open in Course

Longest Substring - Implementation

Complete solution

Here's the solution:

function lengthOfLongestSubstring(s)
    charSet := empty set
    left := 0
    maxLength := 0

    for right from 0 to length of s - 1
        // Shrink window until no repeat
        while s[right] is in charSet
            remove s[left] from charSet
            left := left + 1

        // Expand window
        add s[right] to charSet
        maxLength := max(maxLength, right - left + 1)

    return maxLength

Time: O(n)O(n). Space: O(min(n,m))O(min(n, m)) where mm is the character set size.