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.

GoData Integrity

Code

gosnippet
31 lines
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

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`.