How do I implement two-pointer techniques in Go?

The two-pointer technique is a popular algorithmic approach used to solve problems that involve searching or manipulating arrays or linked lists. This technique involves using two pointers that iterate over the data structure at different speeds or from different directions. It's particularly useful for problems like finding pairs in a sorted array or for merging two sorted lists.

Example Implementation in Go

// Two-pointer technique example in Go
package main

import (
	"fmt"
)

func twoPointerExample(arr []int, target int) (int, int) {
	left, right := 0, len(arr)-1

	for left < right {
		sum := arr[left] + arr[right]
		if sum == target {
			return left, right
		} else if sum < target {
			left++
		} else {
			right--
		}
	}
	return -1, -1 // return -1 if no pair is found
}

func main() {
	arr := []int{1, 2, 3, 4, 6}
	target := 10
	left, right := twoPointerExample(arr, target)
	fmt.Printf("Indices of the elements that sum up to %d are: %d and %d\n", target, left, right)
}

Keywords: two-pointer technique Go programming algorithm array manipulation