Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

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

Posted on August 15, 2021August 15, 2021 by admin

Table of Contents

  • Overview
  • Program

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

  • Number 1 at index 2
  • Number 3 at index 3

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

  • If say one of the numbers is x
  • Then the other number will be target-x

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]
  • go
  • golang
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme