Leetcode Two Sum with Golang and Python

My Lazy but Honest Comeback to LeetCode 😅

Hello everyone! So lately, I’ve been kind of Bored as F and, let’s be real, Unemployed too — which is a weird combo of freedom and existential crisis. 😅
So I thought, “Why not give LeetCode another shot?” It’s been a while, and maybe I’ll end up doing something productive… or at least feel like I’m doing something productive.

The Struggle is Real

The first thing I did was head over to YouTube — you know, the usual scroll through coding tutorials. I was bombarded with tons of videos. I told myself: “Okay, let’s not rush. First watch, understand, then solve.” But no joke — the moment I opened a few videos, all I saw was 5–6 different creators explaining the same question in slightly different ways, and my brain just noped out. Like, it legit started to overheat and self-destruct 💥... so I quietly crawled back into the comfort of anime and movies. 🫠

A Flicker of Motivation: The Classic "Two Sum"

But today, something different happened. Out of pure nostalgia (and maybe guilt), I decided to try the Two Sum problem — a classic I remember dabbling with back in my college days. The first time I attempted it, I used to just head straight to the "Solutions" tab, peek at the answers, tell myself I understood, and then close the tab like I did something smart. After a couple of those, I got bored again and ditched the whole thing.

But now, having worked as a Full Stack Developer for a year and recently resigned, I have a lot more time on my hands. And maybe, just maybe, a better approach to problem-solving. So here I am — back on LeetCode, this time trying to actually solve things and not just pretend.

Now the Boring Part: Solving Two Sum

🐍 Python Version

So I decided to first write the Python solution. To my surprise, it ran in 0 ms with 19.1 MB of memory. Not bad, huh?

Here’s the code I wrote:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dicts = {}
        for key, value in enumerate(nums):
            diff = target - value
            if diff in dicts and dicts[diff] != key:
                return [key, dicts[diff]]
            dicts[value] = key
        return []

🧠 Let's Break It Down

We’re given a list of numbers (nums) and a target integer. The task is to return the indices of the two numbers that add up to the target.

  1. Using a Dictionary (Hash Map):
    I created an empty dictionary dicts to store values as keys and their indices as values. This helps in achieving a quick lookup (O(1) time) instead of searching the whole list again.

  2. Enumerating Through the List:
    Using enumerate(nums) gives both the index (key) and the value (value) at the same time, which is perfect for this use case.

  3. Calculating the Difference:
    We calculate the diff = target - value — basically, the number we want to find to complete the pair.

  4. Checking the Dictionary:
    If this diff is already in the dictionary, and its index is not the same as the current one, we’ve found the pair! Return their indices.

  5. Adding to Dictionary:
    If no pair is found yet, add the current number and its index to the dictionary for future reference.

  6. Return []:
    If no valid pair is found by the end of the loop, just return an empty list.

Honestly, this approach is clean, fast, and memory-efficient. And it felt good writing it from scratch this time.


🧩 GoLang Version

Then I thought, “Hey, let’s try doing the same in Go!” So I fired up my VS Code, switched over to Go, and whipped up this version:

func twoSum(nums []int, target int) []int {
    dicts := make(map[int]int)
    
    for i, num := range nums {
        diff := target - num
        if pres, ok := dicts[diff]; ok {
            return []int{pres, i}
        }
        dicts[num] = i
    }
    
    return nil
}

⚙️ GoLang Breakdown

  1. Map Declaration:
    We use make(map[int]int) to create a map similar to Python’s dictionary.

  2. Looping Over the Slice:
    We loop using range, which gives us both index i and value num.

  3. Difference Check:
    We calculate diff = target - num and then check if it’s present in our map.

  4. Return on Match:
    If found, return the saved index (pres) and the current one.

  5. Otherwise, Add to Map:
    If not found, we store the current number and its index.

  6. Return nil:
    If no pair is found by the end, return nil.

This Go version had a runtime of 1 ms and used 5.9 MB memory, which is pretty solid.


Reflections and Random Thoughts 💭

Writing these solutions today gave me a weird sense of satisfaction. Not because I did anything groundbreaking — it’s still just the Two Sum problem — but because I actually sat down and did it instead of procrastinating endlessly.

Also, I realized how different it feels solving a problem after working in the real world for a year. You think about performance, memory, and structure more. You understand why dictionaries or maps are used instead of brute force loops. And you appreciate clean code more than ever.

Post a Comment

0 Comments