Use two pointers and sliding windows
Use two pointers and sliding windows
Two-pointer techniques move two indices according to an invariant instead of checking all pairs. A sliding window tracks an interval of neighboring elements and updates its summary as the interval moves. These methods reduce repeated work when the input obeys the required conditions.
package main
import ( "fmt")
func pair(a []int, t int) bool { l, r := 0, len(a)-1 for l < r { s := a[l] + a[r] if s == t { return true } if s < t { l++ } else { r-- } } return false}func main() { fmt.Println(pair([]int{1, 2, 4, 7}, 9), pair([]int{1, 2, 4, 7}, 8), pair(nil, 0))}On ascending sorted input, if the sum is too small then even pairing the left value with the largest remaining value fails, so discard that left index. If too large, discard the right index. Each step shrinks the interval: O(n) time and O(1) extra space. This assumes sums fit int and requires two distinct indices.
Expected output:
true true falseFind the maximum fixed-width sum
package main
import ( "fmt")
func maxWindow(a []int, k int) (int, bool) { if k <= 0 || k > len(a) { return 0, false } s := 0 for _, v := range a[:k] { s += v } best := s for i := k; i < len(a); i++ { s -= a[i-k] s += a[i] if s > best { best = s } } return best, true}func main() { fmt.Println(maxWindow([]int{2, -3, 7, 4}, 2)) fmt.Println(maxWindow([]int{-5, -2, -8}, 1)) fmt.Println(maxWindow(nil, 1))}After each shift, subtract the departing element and add the arriving one. Initialize best to the first actual window, not zero, so negative-only data works. O(n) time, O(1) extra space; assumes intermediate sums fit int. A variable-width window for a sum threshold needs additional assumptions (often nonnegative values).
Expected output:
11 true-2 true0 falseTry it locally
Compute every adjacent pair sum of [3,1,5,2] in one pass, printing [4 6 7]. Return an empty slice for fewer than two items.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Algorithms 05: Use two pointers and sliding windows
Check the lesson objective before moving on.
Why can the left index be discarded when a sorted pair sum is too small?
How should best be initialized for maximum fixed-width sum?