July 26, 2025
Question
Given a string s
, find the length of the longest substring without repeating characters.
Example
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke"
, with the length of 3.
My Notes
- We can use a sliding window to keep track of non-repeating characters.
- Two pointers: one expanding (right), one shrinking (left) when a duplicate is found.
- Use a set (map) to track which characters are inside the window.
- Update the result as we go.
Brute Force
package main import ( "fmt" ) func lengthOfLongestSubstring(s string) int { if len(s) < 2 { return len(s) } result := 0 for i := range s { lookup := make(map[string]struct{}) for j := range s[i:] { if _, ok := lookup[string(s[i+j])]; ok { break } if j+1 > result { result = j + 1 } lookup[string(s[i+j])] = struct{}{} } } return result } func main() { result := lengthOfLongestSubstring("pwwkew") fmt.Println(result) }
Optimized Sliding Window
package main import ( "fmt" ) func lengthOfLongestSubstring(s string) int { result := 0 l := 0 lookup := make(map[byte]struct{}) for r := 0; r < len(s); r++ { // If s[r] is in the map, shrink the window from the left for { if _, ok := lookup[s[r]]; !ok { break } delete(lookup, s[l]) l++ } // Add current character to the set lookup[s[r]] = struct{}{} // Update result if r-l+1 > result { result = r - l + 1 } } return result } func main() { result := lengthOfLongestSubstring("pwwkew") fmt.Println(result) }