Two Sum Problem Explained with Python Code

Avatar
M

Maksudur Rahman

Software Engineer

57Views
5mRead
0Reactions

Introduction

The Two Sum problem is one of the first algorithmic problems most people solve when learning Python or preparing for coding interviews. The task is simple to state: given an array of integers and a target value, find two different elements whose sum equals the target, and return their indices.

For example:

nums = [2, 7, 11, 15]

target = 9

Output:[0, 1]

Here, nums[0] + nums[1]equals 9, so the output is[0, 1]. This article explains the problem from first principles, walks through a brute-force approach, then builds up to the optimized dictionary-based solution used in real Python code and interviews.

What Is the Two Sum Problem?

The Two Sum problem gives you an input array of numbers and a target value. Your job is to find two numbers in the array that add up to the target and return their positions (indices), not the values themselves.

A few rules matter here:

  • The same array element cannot be used twice, even if the value could theoretically pair with itself.

  • If no valid pair exists, the function should return an empty result rather than raising an error.

  • The standard formulation asks for indices, since a returned index tells you exactly where each number lives in the original array.

Two Sum Example in Python

Take the same array again:

nums = [2, 7, 11, 15]

target = 9

Checking the first two elements: 2 + 7 = 9, which matches the target. Their indices are 0 and 1, so the expected output is [0, 1]. This small example is used throughout the article to keep the logic easy to follow.

Brute Force Solution for Two Sum

The most direct way to solve Two Sum is to compare every pair of numbers using two nested loops.

def two_sum(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 []

The outer loop picks a starting number, and the inner loop checks every number after it. If a pair adds up to the target, their indices are returned immediately.

Time Complexity: O(n²), since every element is compared against every other element.

Space Complexity: O(1), excluding the returned result.

This approach works correctly, but it becomes slow on large arrays because the number of comparisons grows quadratically.

Optimized Two Sum Solution Using a Python Dictionary

A much faster approach uses a Python dictionary to remember numbers as the array is scanned, avoiding the need for nested loops.

def two_sum(nums, target):

    seen = {}

    for i, num in enumerate(nums):

        complement = target - num

        if complement in seen:

            return [seen[complement], i]

        seen[num] = i

    return []

This dictionary-based, single-pass approach is the standard solution used in Python code and interview settings, because it solves the problem in linear time.

How the Two Sum Python Solution Works

Step 1: Create an empty dictionary. seen = {}will store each number seen so far, mapped to its index (number → index).

Step 2: Loop through the array using enumerate(nums), which provides both the index (i) and the value (num) on each pass.

Step 3: Calculate the complement. complement = target - num tells you what value is needed to reach the target. For target = 9 and num = 2, the complement is 7, so the question becomes: have we already seen 7?

Step 4: Check the dictionary. If complement in seen: means the pair has been found, so the function returns the stored index together with the current index.

Step 5: Store the current number. seen[num] = i saves the current value so future elements can find it as their complement.

Python's documentation describes dictionary membership checks and item access as average-case O(1), which is why this lookup-based approach performs efficiently in typical cases.

Two Sum Python Code Step-by-Step Example

Step

Index

Number

Complement

Dictionary State

1

0

2

7

{2: 0}

2

1

7

2

2 found → match

3

Return [0, 1]

Why Use a Dictionary for Two Sum?

The brute force method checks many other numbers for every number in the array. The dictionary approach flips this idea: for every number, it calculates what value is needed and checks whether that value already exists, avoidingFht repeatedly scanning the array. The algorithm maintains a lookup table while traversing the array once.

Time and Space Complexity

Approach

Time

Space

Brute Force

O(n²)

O(1)

Dictionary / HashMap

O(n) average

O(n)

It is worth noting that Python's documented dictionary complexity is average-case; pathological hash-collision scenarios can behave differently, though this is rare in practice.

Two Sum With Duplicate Numbers

nums = [3, 3]

target = 6

Output:[0, 1]

Here, the first 3 is stored in the dictionary at index 0. When the second 3 is processed, its complement (3) is already in the dictionary, so the pair is found. The algorithm never reuses the same array position twice, which is why this still works correctly with duplicate values.

Two Sum With Negative Numbers

nums = [-3, 4, 7, 2]

target = 1

Output:[0, 1]

Since -3 + 4 = 1, the indices 0 and 1 are returned. The complement calculation works the same way regardless of whether the numbers are positive or negative.

Two Sum When No Solution Exists

nums = [1, 2, 3]

target = 10

Output:[]

The exact return behaviour can depend on how the problem is specified. For a general-purpose tutorial implementation, returning an empty list is a reasonable convention when no valid pair exists.

LeetCode Two Sum Problem in Python

The same dictionary-based logic can be placed inside the class structure commonly used on coding platforms:

class Solution:

    def twoSum(self, nums, target):

        seen = {}

        for i, num in enumerate(nums):

            complement = target - num

            if complement in seen:

                return [seen[complement], i]

            seen[num] = i

This one-pass dictionary pattern is a widely used approach for solving Two Sum in Python on platforms like LeetCode.

Two Sum Python vs Brute Force

Feature

Brute Force

Dictionary

Basic idea

Check pairs

Store seen values

Time

O(n²)

O(n) average

Extra space

O(1)

O(n)

Beginner friendly

Yes

Yes

Best for large input

Less efficient

More efficient

Neither approach is simply "better" in every situation — the dictionary method trades extra memory for significantly faster runtime, which is usually the right trade-off for larger inputs.

Common Mistakes in Two Sum

  • Returning the value instead of the index

  • Reusing an element twice

  • Saving the current number to the dictionary before searching for the complement

  • Not considering that negative numbers can be part of the input

  • Mistaking target - num for target + num

  • Having redundant loops when already using the dictionary method

  • Failing to understand the contents of the dictionary (number to index mapping and not vice versa)

  • Incorrectly ordering the output indices

  • Two Sum Variations

    Two Sum II: The input array is sorted, which allows a two-pointer approach instead of a dictionary.

    Two Sum III: A design-oriented version involving repeated additions and lookups over time.

    3Sum: Extends the idea to find three numbers that satisfy a target condition.

    4Sum: Extends the same complement-based thinking to four numbers.

    These variations are commonly discussed together as a single Two Sum problem cluster.

    What You Learn From the Two Sum Problem

    Two Sum is a simple problem, but it introduces multiple transferable techniques such as handling arrays, loop iterations, dictionary manipulation, hashing, using the complement approach, index management, time and space complexity, and optimization of algorithms in general.

    The underlying commonality is storing data while iterating through the array and using the stored data for answering future queries instantly. The same exact approach will be seen in multiple other array/string problems, and that’s why Two Sum is often the first problem presented in an interview prep course.

    Frequently Asked Questions

    What is the Two Sum problem in Python?

    The Two Sum problem asks you to find two numbers in an array that add up to a given target value and return their indices. In Python, it is commonly solved using a dictionary to achieve linear-time performance.

    What is the fastest way to solve Two Sum in Python?

    The fastest common approach uses a single loop with a Python dictionary that stores each number's index. For every element, you check whether its complement (target minus the current number) has already been seen, which solves the problem in O(n) average time.

    What is the time complexity of the Two Sum problem?

    The brute-force solution runs in O(n²) time using nested loops. The optimized dictionary-based solution runs in O(n) average time, using O(n) additional space to store seen numbers.

    Can the Two Sum problem have negative numbers or duplicates?

    Yes. The dictionary-based solution works correctly with negative numbers, since the complement calculation (target minus the current number) is unaffected by sign. It also works with duplicate values, because each number is stored at its own index and the same index is never reused.

    Related Reading

    Python Dictionaries Explained

    • Python Lists and Arrays

    • Python Loops

    • Big O Notation Explained

    • Hash Tables in Python

    • HashMap vs Dictionary

    • Two Sum II

    • 3Sum Problem

    • 4Sum Problem

    • Binary Search in Python

    • Sliding Window Problems

    • Common Python Coding Interview Problems

    Recommended Resources & Courses

    React to this article