Leetcode Diaries: 3Sum – The Trio We Never Asked For
Hey folks!
Today’s another day in this thrilling journey of unemployment—and as usual, I decided to wake up, drink a cup of chai, and torture myself with another Leetcode “fun” ride. And the star of today’s show is one of the most classic medium-level problems out there:
15. 3Sum
This one has haunted many and humbled more. But today, I finally sat down, opened VS Code, and made it happen. So here I am sharing my approach in Python and Golang, along with performance stats and thoughts along the way. Where i made about 10-13 prerenders to avoid time-exceeding errors which i started by 103/314 to 305/314 and lastly 312/314 edge cases. as time goes on i got the hinge of it as i made multiple bruteforce changes where i initially not using pointers or any short hand methods in leetcode answers.
💡 What is 3Sum?
The goal of this problem is pretty simple to understand (and not-so-simple to solve efficiently at first glance):
Given an array
nums
, return all the unique triplets[nums[i], nums[j], nums[k]]
such that the sum is zero:
nums[i] + nums[j] + nums[k] == 0
Here’s the catch: The solution set must not contain duplicate triplets.
🐍 Python Solution
🧠 Explanation
-
First, I handled edge cases like when all elements are
0
, or when the array only contains0
,1
, and-1
. -
The core logic uses a hash set to avoid duplicates and optimize lookup for the third number.
-
Each potential triplet is sorted and stored as a tuple in a set to ensure uniqueness.
-
At the end, the set is converted into a list of lists.
📊 Python Results
-
⏱ Runtime: 882 ms
-
🧠 Memory: 22.3 MB
Not the fastest out there, but a solid solution to start with—especially for clarity and readability.
⚙️ Golang Solution
🧠 Explanation
-
Very similar approach to the Python version but more verbose due to Go’s strict typing.
-
Used maps to simulate hash sets and eliminate duplicates.
-
Manual sorting of triplets using conditional swaps.
-
Used helper functions for value counting and extracting unique values from the array.
📊 Golang Results
-
⏱ Runtime: 747 ms
-
🧠 Memory: 20 MB
Go did a great job here, being both faster and more memory-efficient than Python. It’s no surprise, but it feels rewarding to see it in numbers.
🎯 Final Thoughts
What I loved about solving 3Sum today is how many edge cases it forces you to think about. From duplicates, to the triple zero scenario, to performance concerns—it’s a compact package of algorithmic thinking.
If you’re also in a weird life stage like me, floating between jobs or just sharpening your DSA sword, this is a great problem to try out.
✔️ Key Takeaways:
-
Always handle special and edge cases first.
-
Use sets/maps for de-duplication.
-
Sort the triplets before storing.
-
Don't be afraid to write a brute-force + optimized logic mix in your first go. Clean code comes after clarity.
See you in the next one. 🏃➡️🏃➡️🏃➡️
0 Comments