Finding the Longest Substring Without Repeating Characters via Sliding Window
This article explains how to solve the classic “longest substring without repeating characters” problem using a sliding‑window technique, detailing pointer management, duplicate detection, and a complete Go implementation.
The task is to determine the maximum‑length substring of a given string that contains no repeated characters.
The solution relies on a sliding‑window approach: two pointers, left and right, both start at 0. right moves forward one character at a time, while the window’s contents are tracked to ensure all characters are unique. When a duplicate appears, left advances to discard characters until the window becomes valid again.
Typical pseudocode:
define left = 0, right = 0
define win to store results
while right is within bounds:
add s[right] to win
right++
while win does not satisfy uniqueness:
remove s[left] from win
left++The core check is whether any character between left and right repeats.
Complete Go code:
func lengthOfLongestSubstring(s string) int {
// sliding window boundaries
left, right := 0, 0
// count of characters in the window
win := make(map[byte]int)
result := 0
max := func(a, b int) int {
if a > b {
return a
}
return b
}
for right < len(s) {
ch := s[right] // current character
right++
win[ch]++ // increment count
for win[ch] > 1 { // duplicate found, shrink window
d := s[left]
left++
win[d]--
}
// window is valid, update result
result = max(result, right-left)
}
return result
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Nullbody Notes
Go backend development, learning open-source project source code together, focusing on simplicity and practicality.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
