DEV Community

Cover image for Journey into GoLang: Understanding Go by solving LeetCode problems
Mohammed Nadeem Shareef
Mohammed Nadeem Shareef

Posted on

Journey into GoLang: Understanding Go by solving LeetCode problems

Introduction:

Welcome to the first post of my "Journey into GoLang" series! In this series, I'll be documenting my exploration of GoLang programming through solving LeetCode problems. Today, we kick off our journey by solving the classic Two Sum problem.

The Problem Description:

Given an array of integers and a target integer, find the indices of two numbers that add up to the target.

Initial Solution

func twoSum(nums []int, target int) [2]int {
  result := [2]int{}
  for i := 0; i < len(nums); i++ {
    for j := 0; j < len(nums); j++ {
      if i == j {
        continue;
      }

      if nums[i] + nums[j] == target {
        result[0] = j;
        result[1] = i;
      }
    }
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode

In our initial approach, we took a straightforward route. We add nested loops to iterate through the array and find the desired indices. While this solution worked, it had a time complexity of O(n^2), making it suboptimal for larger datasets.

Optimized Solution

func optimizeTwoSum(nums []int, target int) [2]int {
  result := [2]int{}
  m := make(map[int]int)
  for i := 0; i < len(nums); i++ {
    m[nums[i]] = i
  }

  for i := 0; i < len(nums); i++ {
    if _, ok := m[target - nums[i]]; ok && m[target - nums[i]] != i {
      result[0] = i
      result[1] = m[target - nums[i]]
      break
    }
  }
  return result
}
Enter fullscreen mode Exit fullscreen mode
  • We create a hash map, hash map keys are the values of nums and the hash map value is an index of the value of nums.
  • We use the hash map to find the complement of the target.
  • Complement means the difference between the target and the value of nums (x + y = t => x = t - y).
  • If the complement exists in the hash map, we return the index of the complement and the index of the value of nums.
  • Map returns two values, the first value is a value stored under the key, and the second value is a boolean indicating whether the key exists or not.
  • If the requested key doesn’t exist, we get the value type’s zero value. In this case, the value type is int, so the zero value is 0. The second value will be false.

Github Code Link

Join the Journey:
This post marks just the beginning of our journey into GoLang and algorithmic problem-solving. Stay tuned for more insights, challenges, and optimizations as we delve deeper into the world of programming.

Conclusion:
As we conclude our first installment of the "Journey into GoLang" series, I invite you to learn with me. Together, let's understand GoLang, one LeetCode problem at a time.

Thank you for joining me on this journey, and I look forward to sharing more discoveries with you in the upcoming posts!

Social Links

Top comments (0)