DEV Community

Mahdi Shamlou | Solving LeetCode #1: Two Sum — The Classic Hash Map Solution

Hey everyone! I’m Mahdi Shamlou, and I’m starting a new series on classic LeetCode problems. Let’s kick it off with the very first one: Problem #1 — Two Sum.

This is an Easy difficulty problem, but it’s legendary — it’s often the very first question in coding interviews at big tech companies. Solving it optimally shows you understand one of the most powerful tools in programming: hash maps (dictionaries in Python).
Problem Statement: Two Sum

Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.

You may assume that each input has exactly one solution, and you may not use the same element twice. You can return the answer in any order.

Examples:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: nums[0] + nums[1] = 2 + 7 = 9

Input: nums = [3,2,4], target = 6
Output: [1,2]

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

The Optimal Approach: One-Pass Hash Map

The brute force way would be to check every pair with two nested loops — that’s O(n²) time, which is too slow for large arrays.

Instead, we use a dictionary to store numbers we’ve seen so far and their indices.
Become a member

As we iterate through the array:

For each number nums[i], calculate the target_less:
target — nums[i] 0 If the target_less is already in the dictionary, we’ve found our pair!
Otherwise, add the current number and its index to the dictionary.
This is one pass through the array → O(n) time and O(n) space.

Here’s the Python solution:

class Solution(object):
    def twoSum(self, nums, target):
        dict_key = {}

        for i, num in enumerate(nums):
            target_less = target - num

            if target_less in dict_key:
                return [dict_key[target_less], i]

            dict_key[num] = i
Enter fullscreen mode Exit fullscreen mode

Why is this approach great?

Super efficient: Beats 95%+ of submissions on LeetCode in time
Clean and readable: Easy to explain in interviews
Handles edge cases perfectly : like duplicate numbers

If you know other methods feel free to share in the comments! I’d love to learn and maybe create a separate post about them 🚀

Any questions? I’m happy to help!

Connect with me:

🔗 LinkedIn: https://www.linkedin.com/in/mahdi-shamlou-3b52b8278

📱 Telegram: https://telegram.me/mahdi0shamlou

📸 Instagram: https://www.instagram.com/mahdi0shamlou/

Author: Mahdi Shamlou | مهدی شاملو

Top comments (0)