Two Sum in Python

The Two Sum problem is a classic coding challenge where you find two numbers in an array that add up to a specific target. Given an array of integers and a target sum, return the indices of the two numbers that add up to the target.

For example, if the array is [2, 8, 12, 15] and the target is 20, the solution returns indices [1, 2] because 8 + 12 = 20.

Algorithm Approach

We use a hash map (dictionary) to store each number and its index as we iterate through the array. For each element, we check if its complement (target ? current number) exists in the hash map ?

  • Create an empty dictionary to store numbers and their indices
  • For each number in the array:
    • Calculate the complement: target ? current_number
    • If complement exists in dictionary, return both indices
    • Otherwise, store current number and its index in dictionary

Implementation

def two_sum(nums, target):
    """
    Find two numbers that add up to target and return their indices
    """
    required = {}
    
    for i in range(len(nums)):
        complement = target - nums[i]
        
        if complement in required:
            return [required[complement], i]
        else:
            required[nums[i]] = i
    
    return []  # No solution found

# Example usage
input_list = [2, 8, 12, 15]
target = 20

result = two_sum(input_list, target)
print(f"Input: {input_list}")
print(f"Target: {target}")
print(f"Indices: {result}")
print(f"Values: [{input_list[result[0]]}, {input_list[result[1]]}]")
Input: [2, 8, 12, 15]
Target: 20
Indices: [1, 2]
Values: [8, 12]

How It Works

Let's trace through the example step by step ?

def two_sum_with_trace(nums, target):
    required = {}
    print(f"Looking for two numbers that sum to {target}")
    
    for i in range(len(nums)):
        complement = target - nums[i]
        print(f"Index {i}: nums[{i}] = {nums[i]}, complement = {complement}")
        
        if complement in required:
            print(f"Found! {complement} is at index {required[complement]}")
            return [required[complement], i]
        else:
            required[nums[i]] = i
            print(f"Stored: required[{nums[i]}] = {i}")
    
    return []

# Trace the execution
nums = [2, 8, 12, 15]
target = 20
result = two_sum_with_trace(nums, target)
Looking for two numbers that sum to 20
Index 0: nums[0] = 2, complement = 18
Stored: required[2] = 0
Index 1: nums[1] = 8, complement = 12
Stored: required[8] = 1
Index 2: nums[2] = 12, complement = 8
Found! 8 is at index 1

Time and Space Complexity

Aspect Complexity Explanation
Time O(n) Single pass through array
Space O(n) Hash map storage

Alternative Solutions

Brute Force Approach

def two_sum_brute_force(nums, target):
    """
    Brute force approach - check all pairs
    Time: O(n²), Space: O(1)
    """
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]
    return []

# Test brute force
nums = [2, 8, 12, 15]
result = two_sum_brute_force(nums, 20)
print(f"Brute force result: {result}")
Brute force result: [1, 2]

Conclusion

The hash map approach solves Two Sum in O(n) time by storing complements as we iterate. This is more efficient than the O(n²) brute force method and is the preferred solution for this classic problem.

Updated on: 2026-03-25T07:06:54+05:30

19K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements