Two Sum LeetCode Solution: Optimal Approach (Data-Backed Guide)

By DSA Prep Team · March 4, 2026 · 8 min read · Algorithms

If you think LeetCode #1 is too basic to matter in a real interview, the data says otherwise.

We analyzed 10,385 verified interview questions across 259 companies. Two Sum ranked #1 globally — with 170 confirmed appearances at 70 different companies including Amazon, Google, Meta, Bloomberg, and Microsoft.

Interviewers don't ask Two Sum to test your genius. They ask it as a warm-up, a filter, and a communication test. Stumble here and the interview is effectively over. Nail it in 5 minutes with a clean explanation and you set a strong tone for every round that follows.

Table of Contents

The Data: Why This Problem Still Gets Asked

Most candidates assume Two Sum is a throwaway warm-up that barely matters. The company-wise data tells a different story.

Metric Value
Total Interview Appearances170 verified mentions
Companies That Ask It70 companies
Global Rank#1 out of 10,385 questions
DifficultyEasy (the follow-ups are not)
Core PatternHash Map / Complement Lookup

Two Sum is asked more than any other LeetCode problem not because it's hard, but because it tests three things simultaneously: pattern recognition (can you see the hash map approach?), optimization instinct (can you move from O(n²) to O(n)?), and communication (can you explain your reasoning clearly before writing code?).

Problem Statement

LeetCode #1 — Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume exactly one solution exists, and you may not use the same element twice.

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

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

Input:  nums = [3, 3], target = 6
Output: [0, 1]   // Edge case: duplicate values

The Trap: Brute Force Approach

Under pressure, your brain defaults to the simplest path: check every pair. This is the nested loop approach.

Python — Brute Force O(n²)
def twoSum(nums, target):
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]
    return []
MetricBrute ForceOptimal
Time ComplexityO(n²)O(n)
Space ComplexityO(1)O(n)
Passes Interview?❌ Not if you stop here✅ Yes

⚠️ What to Say in the Interview

Mentioning the brute force is fine — stopping there is not. Always lead with:

"The naive approach is nested loops — O(n²) time, O(1) space. But we can trade some space for time and bring that down to O(n) using a Hash Map. Let me walk you through that."

This signals problem-solving maturity. You show you know multiple approaches before jumping to the best one.

The Optimal Approach: One-Pass Hash Map

The key insight: instead of asking "does any pair sum to target?", reframe it as "have I already seen the complement of this number?"

If target = 9 and the current number is 2, you don't need to scan the array — you're looking for exactly one number: 9 - 2 = 7. Store every number you've seen in a Hash Map with its index. If the complement is already there, you're done.

Step-by-Step Logic

  1. Create an empty Hash Map: { value → index }
  2. Iterate through the array once
  3. For each number, calculate complement = target - num
  4. If complement is in the map → return [map[complement], current_index]
  5. Otherwise → store num: index in the map and continue

Visual Walkthrough

Tracing nums = [3, 2, 4], target = 6:

StepinumcomplementIn map?map state
1033No{3: 0}
2124No{3: 0, 2: 1}
3242Yes → index 1Return [1, 2]

Code in Python, Java & JavaScript

Python 3
def twoSum(nums: list[int], target: int) -> list[int]:
    seen = {}  # value -> index

    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i

    return []  # guaranteed solution exists per constraints
Java
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> seen = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (seen.containsKey(complement)) {
                return new int[]{ seen.get(complement), i };
            }
            seen.put(nums[i], i);
        }

        return new int[]{};  // never reached
    }
}
JavaScript
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    const seen = new Map();  // value -> index

    for (let i = 0; i < nums.length; i++) {
        const complement = target - nums[i];
        if (seen.has(complement)) {
            return [seen.get(complement), i];
        }
        seen.set(nums[i], i);
    }

    return [];
};

Complexity Analysis

When you finish writing the code, the interviewer's next question is almost always: "What are the time and space complexities?" Know this cold.

📊 Complexity Summary

The trade-off statement for your interview: "We're trading O(1) space from the brute force for O(n) extra space, in exchange for dropping time from O(n²) to O(n). For large inputs, this is almost always the right trade-off."

Interview Follow-Ups & Variations

A strong Two Sum answer often triggers follow-up questions to test how deeply you understand the pattern. Be ready for all three.

Variation 1: Array is Already Sorted (LeetCode #167)

"What if the array were sorted? Can you do it in O(1) space?"

Answer: Two Pointers. Place left = 0 and right = n-1. If the sum is too big, move right left. If too small, move left right. This gives O(n) time and O(1) space — no hash map needed because sorting gives you directional information for free.

Python — Two Pointers (Sorted Input)
def twoSum_sorted(numbers, target):
    left, right = 0, len(numbers) - 1

    while left < right:
        total = numbers[left] + numbers[right]
        if total == target:
            return [left + 1, right + 1]  # 1-indexed per LC #167
        elif total < target:
            left += 1
        else:
            right -= 1

    return []

Variation 2: Multiple Valid Pairs

"What if there are multiple pairs that sum to target? Return all of them."

Answer: The hash map approach still works, but you must handle duplicates and collect all pairs instead of returning immediately. This is the core mechanic behind 3Sum (LeetCode #15) and 4Sum (LeetCode #18), which you should solve next.

Variation 3: Design a Data Structure (LeetCode #170)

"Design a class that supports add(number) and find(target) operations on a running stream of numbers."

Answer: Maintain a hash map of value frequencies. add() is O(1). find() iterates the map keys and checks for each key's complement — O(n) time. This tests whether you can extend a pattern into an OOP design context.

How to Actually Remember This

Two Sum is asked by 70 companies. You cannot afford to blank on it. But more importantly, the Hash Map complement pattern is the backbone of at least 15 other LeetCode problems:

Memorizing the code won't help. You need to understand why the complement insight works, and practice retrieving it under pressure. That means spaced repetition.

✅ Your Review Schedule for Two Sum

  1. Today (Day 0): Solve it from scratch. Time yourself. Write the hash map approach without referring to this guide.
  2. Day 3: Re-solve without looking at code. Explain the "complement" insight out loud as if teaching it.
  3. Day 7: Write all three language versions (Python, Java, JS) on paper without IDE autocomplete.
  4. Day 14: Solve Two Sum II (sorted) and one related problem (e.g., Subarray Sum Equals K).
  5. Day 30: Quick pattern check — can you still state the O(n) approach and both complexities in under 60 seconds?

Instead of manually tracking these review dates, use DSAPrep.dev Tracker to log Two Sum. Tag it under Hash Map and Arrays and the system auto-schedules your Day 1, Day 3, Day 7, Day 14, and Day 30 reviews for you.

Track Your Progress on DSAPrep.dev →

One problem at a time. One review at a time. Future you will thank present you.