Rabi Siddique
265 words
1 minutes
Solving the Two Sum Problem in Go

The Two Sum problem is a common algorithmic challenge that involves finding two numbers in an array that add up to a specific target. Here’s a solution in Go, along with explanations of the key concepts used.

package main

import "fmt"

func twoSum(nums []int, target int) []int {
    // Declare a hashmap to store the numbers and their indices
    var counter = make(map[int]int)

    // Populate the hashmap with the numbers and their indices
    for i := 0; i < len(nums); i++ {
        counter[nums[i]] = i
    }

    // Iterate through the array to find the two numbers that add up to the target
    for i := 0; i < len(nums); i++ {
        diff := target - nums[i]
        // Check if the difference is in the hashmap and the indices are not the same
        index, exists := counter[diff]
        if exists && index != i {
            return []int{i, counter[diff]}
        }
    }

    // Return nil if no such pair is found
    return nil
}

func main() {
    // Example usage of the twoSum function
    nums := []int{2, 7, 11, 15}
    target := 9
    result := twoSum(nums, target)
    fmt.Println(result) // Output: [0 1]
}

Key Concepts Learned#

  • Using a HashMap in Go: You use the make function to declare a hashmap.
  • Retrieving Values from a HashMap: When you retrieve a value from a hashmap, both the value and a boolean variable are returned. The boolean indicates if the value is present in the hashmap.
  • Looping through an Array: Using a for loop to iterate over array elements.
  • Returning an Array: Returning an array (or slice) from a function.
  • Conditional AND in Go: Using && to combine conditions.
Solving the Two Sum Problem in Go
https://rabisiddique.com/posts/two-sum-go/
Author
Rabi Siddique
Published at
2024-02-10