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
- 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)
}
}
- Given a list of
studentNames
, go one by one and mark them as present in apresence
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
}
- Given a list of numbers, and an integer called
num
, write a function that displays the difference betweennum
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)
}
}
- Given a
map[int]bool
write a function that returns"Happy!"
if an integernum
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!"
}