Sliding window
A sliding window maintains a contiguous subslice [left, right) that grows and shrinks as right advances. Each index enters and leaves the window at most once, so the scan is O(n).
Detailed Explanation
You want the longest substring with at most k distinct runes, or the smallest subarray whose sum is at least target. A nested loop over every pair of ends is O(n²). A window keeps the current candidate and updates a running sum or a count map as the ends move.
Grow the right end. For each right, include s[right] in the window state. Then, while the window is invalid, exclude s[left] and increment left. After the while, the window is the best (or the current valid) range ending at right. Record the answer (max(len), min(len), a copy of the slice).
The state must be undoable. A sum is undoable: subtract s[left]. A frequency map is undoable: decrement and delete at zero. A hash of the whole window that you cannot update incrementally is the wrong state — you would recompute in O(n) per move.
Fixed vs variable width. A fixed window of size k is simpler: add s[i], subtract s[i-k] when i >= k. Variable windows use the while-invalid shrink. Empty windows are valid for some problems (max empty is 0) and invalid for others (min empty should not win).
Go storage. For bytes, []byte or string with byte indexes. For runes, convert to []rune first if you mean characters, or range carefully and store byte indexes. A map[rune]int is the usual distinct-count state. For ASCII, [256]int avoids the map.
What it costs. Time O(n) when each end moves only forward, plus the cost of the state update. Space is the state (O(1) for a sum, O(k) for a map of distinct keys). Copying the window on every improvement is O(n²) in the worst case; store indexes and copy once at the end.
Code Examples
package main
import "fmt"
func minLenAtLeast(s []int, target int) int {
left, sum, best := 0, 0, len(s)+1
for right, v := range s {
sum += v
for left <= right && sum >= target {
if right-left+1 < best {
best = right - left + 1
}
sum -= s[left]
left++
}
}
if best == len(s)+1 {
return 0
}
return best
}
func main() {
fmt.Println(minLenAtLeast([]int{2, 3, 1, 2, 4, 3}, 7)) // 2
}func maxWindow(s []int, k int) int {
if k <= 0 || k > len(s) {
return 0
}
sum := 0
for i := 0; i < k; i++ {
sum += s[i]
}
best := sum
for i := k; i < len(s); i++ {
sum += s[i] - s[i-k]
if sum > best {
best = sum
}
}
return best
}Common Gotchas
Shrinking past `right` corrupts the sum
keep `left <= right+1` and handle empty windows on purpose.
Rune problems on a `string` need rune-aware indexes
a byte window is the wrong unit for Unicode text.
If the shrink condition is wrong, the window never moves and you get `O(n²)` any
If the shrink condition is wrong, the window never moves and you get `O(n²)` anyway