DEV Community

coderazade
coderazade

Posted on

LeetCode Go #1. Two sum

Problem Description

You can find the problem on Leetcode.

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: The sum of 2 and 7 is 9. Therefore, the indices of the two numbers are 0 and 1.
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Enter fullscreen mode Exit fullscreen mode

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]
Enter fullscreen mode Exit fullscreen mode

Understand Problem

We are given an array of integers and a target value. Our task is to find two numbers in the array that add up to the target value. We need to return the indices of these two numbers.

Implementation

Let's implement the solution in Go.

package main

func twoSum(nums []int, target int) []int {
    complements := make(map[int]int)

    for i, num := range nums {
        complement := target - num
        if index, found := complements[complement]; found {
            return []int{index, i}
        }
        complements[num] = i
    }

    return nil
}
Enter fullscreen mode Exit fullscreen mode

Testing

To test the solution, we can use the testing package in Go. We'll write multiple test cases to ensure our implementation works as expected.

package main

import (
    "reflect"
    "testing"
)

func TestTwoSum(t *testing.T) {
    tests := []struct {
        nums   []int
        target int
        want   []int
    }{
        {[]int{2, 7, 11, 15}, 9, []int{0, 1}},
        {[]int{3, 2, 4}, 6, []int{1, 2}},
        {[]int{3, 3}, 6, []int{0, 1}},
    }

    for _, test := range tests {
        got := twoSum(test.nums, test.target)
        if !reflect.DeepEqual(got, test.want) {
            t.Errorf("Input: nums=%v, target=%d\nGot: %v\nWant: %v", test.nums, test.target, got, test.want)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Congratulations! You have successfully solved the Two Sum problem on Leetcode. By solving this problem, you have learned how to find two numbers in an array that add up to a specific target value. This problem is a classic example of using a map (or dictionary) to store complements and perform efficient lookups.

Now that you are familiar with solving this problem, you can move on to the next challenges on Leetcode and continue improving your problem-solving skills. Good luck!

Top comments (0)