Welcome To Golang By Example

Find two numbers in an array that adds up to a target number in Go (Golang)

Table of Contents

Overview

For example, let’s say we have a given array

[2, 5, 1, 3]

The target number is 4

Then the answer will be index

[2, 3]

as we have

and 1+3 = 4

Do note that the array is unsorted

Expected TC – O(n)

We can use a hash for the solution. It is based upon the idea that

So if for a number x we check that target-x is in the hash. If it is then we know we have the solution

Let’s see a program for the same.

Program

package main

import "fmt"

func main() {
	output := twoTargetSums([]int{2, 5, 1, 3}, 4)
	fmt.Println(output)
}

func twoTargetSums(nums []int, target int) []int {
	numberMap := make(map[int]int)
	output := make([]int, 2)
	for i := 0; i < len(nums); i++ {
		val, ok := numberMap[target-nums[i]]
		if ok {
			output[0] = val
			output[1] = i
			return output
		} else {
			numberMap[nums[i]] = i
		}
	}
	return output
}

Output

[2 3]