Fundamentals 3 min read

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.

Nullbody Notes
Nullbody Notes
Nullbody Notes
Finding the Longest Substring Without Repeating Characters via Sliding Window

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
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

algorithmGosliding windowhash maplongest substring
Nullbody Notes
Written by

Nullbody Notes

Go backend development, learning open-source project source code together, focusing on simplicity and practicality.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.