Optimizing Two Sum with Hash Map

Day 4 of #200DaysOfCode! 🚀 After tackling "3Sum" yesterday, I decided to circle back to the problem that started it all for many of us: "Two Sum" (LeetCode 1). While this is often the first problem developers solve, revisiting it with a focus on optimization is always valuable. The Strategy: Space vs. Time Yesterday, for 3Sum, I used sorting and pointers to save space. Today, for Two Sum, I used a Hash Map (Dictionary) to maximize speed. The Logic (One-Pass Hash Map): Instead of using a nested loop to find a pair (which would be a slow O(N^2)), I utilized a dictionary to "remember" the numbers I've seen so far. Iterate through the array. Calculate the complement: diff = target - nums[i]. Check if this diff already exists in our dictionary. If yes, we found our pair! Return the indices immediately. If no, store the current number and its index in the dictionary for future lookups. This approach trades a bit of memory O(N) for a massive gain in speed, bringing the time complexity down to a linear O(N). The Result: My Python solution hit a perfect 0 ms runtime, beating 100.00% of submissions. ⚡ It’s fascinating how different data structures (Hash Maps vs. Pointers) solve similar "Sum" problems in completely different ways. Day 4 down. The foundation is solid. 🧱 Which pattern do you prefer implementing: The "Two Pointer" dance or the "Hash Map" lookup? 👇 #200DaysOfCode #Python #LeetCode #TwoSum #Algorithms #HashMap #DataStructures #ProblemSolving #DeveloperJourney #Optimization

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories