How to implement the two sum algorithm to find two values in array that add up to target with Go

1 Answer

0 votes
package main

import (
    "fmt"
)

// TwoSum function to find indices of two numbers that add up to the target
func TwoSum(arr []int, target int) [2]int {
    for i := 0; i < len(arr); i++ {
        for j := i + 1; j < len(arr); j++ {
            if arr[i]+arr[j] == target {
                return [2]int{i, j} // Return indices
            }
        }
    }
    return [2]int{-1, -1} // No match found
}

func main() {
    array1 := []int{1, 5, 7, 4, 3, 2}
    array2 := []int{3, 1, 4, 2, 5}

    // Finding pairs
    result1 := TwoSum(array1, 9)
    result2 := TwoSum(array2, 8)

    // Print results
    fmt.Println("TwoSum([1, 5, 7, 4, 3, 2], 9) =>", result1)
    fmt.Println("TwoSum([3, 1, 4, 2, 5], 8) =>", result2)

    // Extract values based on indices found
    fmt.Println("Numbers:", array1[result1[0]], "and", array1[result1[1]])
}



/*
run:

TwoSum([1, 5, 7, 4, 3, 2], 9) => [1 3]
TwoSum([3, 1, 4, 2, 5], 8) => [0 4]
Numbers: 5 and 4

*/

 



answered May 22, 2025 by avibootz
...