Two-Pointer Scan Finds Pair Sum
Two indices walking inward from both ends of a sorted slice locate a pair summing to the target in one pass, discarding one impossible element per step.
Code
package main
import "fmt"
// pairSum 在升序切片里找和为 target 的两个下标:
// 双指针从两端收拢,每一步淘汰一个不可能的元素,单次遍历即可完成
func pairSum(sorted []int, target int) (int, int, bool) {
left, right := 0, len(sorted)-1
for left < right {
sum := sorted[left] + sorted[right]
switch {
case sum == target:
return left, right, true
case sum < target:
left++ // 和太小:只有左指针右移能变大
default:
right-- // 和太大:只有右指针左移能变小
}
}
return 0, 0, false
}
func main() {
sorted := []int{2, 7, 11, 15, 19, 30}
if i, j, ok := pairSum(sorted, 26); ok {
fmt.Printf("indices %d,%d values %d+%d=%d\n", i, j, sorted[i], sorted[j], 26)
}
if _, _, ok := pairSum(sorted, 100); !ok {
fmt.Println("no pair for target 100")
}
}How the snippet works
Under the hood: the functions pairSum and main.
One loop does the cycling here: for left < right.
Points of care
- Built-in APIs only — no supply chain needs to be vetted.
Using it
The one signature that matters here is func pairSum(sorted []int, target int) (int, int, bool)
Each step the file takes is announced in the output: indices, no pair for target 100.
Execute the file and main walks through pairSum, in that order.
The key statements, annotated
func main() {
sorted := []int{2, 7, 11, 15, 19, 30}
if i, j, ok := pairSum(sorted, 26); ok {
fmt.Printf("indices %d,%d values %d+%d=%d\n", i, j, sorted[i], sorted[j], 26)
}
if _, _, ok := pairSum(sorted, 100); !ok {
fmt.Println("no pair for target 100")
}
}
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSON Pointer EvaluatorEvaluate RFC 6901 JSON Pointer strings against a JSON document to extract the referenced value, with tilde-slash escape handling.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Two-Pointer Scan Finds Pair Sum print when run?
- Run it as a complete program — the output lines carry labels such as `indices`, `no pair for target 100`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.