Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

Solution in Go

func twoSum(nums []int, target int) []int {
    result := make([]int, 2)
    numIndex := make(map[int]int) // number -> index mapping
    
    for i, n := range nums {
        want := target - n
        
        wantIndex, contains := numIndex[want]
        if contains {
            result[0] = wantIndex
            result[1] = i
            break
        }
        
        numIndex[n] = i
    }
    
    return result
}
Subscribe via email

Get notified once/twice per month when new articles are published.

Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.