Sobes.tech
Senior

// Given an array of integers nums and an integer target // Find two numbers whose sum equals target and return their indices // Assume there is exactly one solution and you cannot use the same element twice // The answer can be returned in any order // Examples: // [2,7,11,15], target = 9, answer [0,1] (nums[0] + nums[1] == 9) // [3,2,4], target = 6, answer [1,2] (nums[1] + nums[2] == 6) // [3,3], target = 6, answer [0,1] (nums[0] + nums[1] == 6)

sobes.tech AI

Answer from AI

Below is an example of solving a problem in Go using a hash table to find a pair of numbers whose sum equals the target:

func twoSum(nums []int, target int) []int {
    indices := make(map[int]int) // key — number, value — index
    
    for i, num := range nums {
        complement := target - num
        if j, found := indices[complement]; found {
            return []int{j, i}
        }
        indices[num] = i
    }
    return nil // if no solution exists (there is always one per the problem statement)
}

// Example usage:
// nums := []int{2,7,11,15}
// target := 9
// result := twoSum(nums, target) // result == [0,1]

Idea: iterate through the array, for each element check if we have previously encountered a number that, when added to the current one, equals the target. If yes — return the indices.