Skip to main content

Two Number Sum

The Problem

Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum up to the target sum, the function should return them in an array, in any order. If no two numbers sum up to the target sum, the method should return an empty array.

Note that the target sum has to be obtained by summing two different integers in the array; you can't add a single integer to itself in order to obtain the target sum.

You can assume that there will be at most one pair of numbers summing up to the target sum.

Solution:

package main

func TwoNumberSum(array []int, target int) []int {
cache := make(map[int]bool)

for _, v := range array {
potentialMatch := target - v

if _, ok := cache[potentialMatch]; ok {
return []int{v, potentialMatch}
}


cache[v] = true
}

return []int{}
}

Complexity: O(n) space, O(n) time

Simplification

  1. Given a list of numbers, write a function that prints them one by one.
package main

import "fmt"

func main() {
numbers := []int{74, 30, -2}
printThem(numbers)
}

func printThem(s []int) {
for _, v := range s {
fmt.Println(v)
}
}

  1. Given a list of studentNames, go one by one and mark them as present in a presence map.
package main

import "fmt"

func main() {
students := []string{"Andrei", "John", "Melissa"}

p := markPresence(students)

fmt.Println("Presence is", p)
}

func markPresence(students []string) map[string]bool {
result := make(map[string]bool)

for _, v := range students {
result[v] = true
}

return result
}

  1. Given a list of numbers, and an integer called num, write a function that displays the difference between num and each number.
package main

import "fmt"

func main() {
nums := []int{3, 44, 54, 33, 1, 5}

displayDifference(10, nums)

}

func displayDifference(target int, nums []int) {
for _, v := range nums {
diff := target - v
fmt.Println(diff)
}
}

  1. Given a map[int]bool write a function that returns "Happy!" if an integer num exists in the map, or "Sad!" if the number is not in the map.
package main

import "fmt"

func main() {
numbers := map[int]bool{10: true, 11: true, 12: true}

fmt.Println(happyOrSad(numbers, 14))
}

func happyOrSad(m map[int]bool, num int) string {
if _, exists := m[num]; exists {
return "Happy!"
}
return "Sad!"
}