Python Program for Two Sum Problem

The Two Sum problem is one of the most popular coding interview questions.

You are given an array and a target sum, and you must find two numbers that add up to the target.

1. Understanding the Problem

Find indices or values of two numbers in an array that add up to a given target.

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

2. Method 1: Brute Force

Python
Check all pairs
def two_sum(nums, target):
    n = len(nums)
    for i in range(n):
        for j in range(i+1, n):
            if nums[i] + nums[j] == target:
                return [i, j]

print(two_sum([2,7,11,15], 9))

Simple but O(n²) complexity.

3. Method 2: Using Hash Map

Python
Optimized solution
def two_sum(nums, target):
    seen = {}

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

print(two_sum([2,7,11,15], 9))

Efficient O(n) solution using dictionary.

4. Method 3: Two Pointer (Sorted Array)

Python
Sorted approach
def two_sum_sorted(nums, target):
    nums = sorted([(num, i) for i, num in enumerate(nums)])
    left, right = 0, len(nums) - 1

    while left < right:
        s = nums[left][0] + nums[right][0]
        if s == target:
            return [nums[left][1], nums[right][1]]
        elif s < target:
            left += 1
        else:
            right -= 1

print(two_sum_sorted([2,7,11,15], 9))

Uses sorting + two pointers for efficiency.

5. Method 4: Function Wrapper

Python
Reusable function
def two_sum(nums, target):
    lookup = {}
    for i, n in enumerate(nums):
        if target - n in lookup:
            return (lookup[target - n], i)
        lookup[n] = i

    return None

print(two_sum([3,2,4], 6))

Clean reusable implementation.

6. Method 5: Handling Edge Cases

Python
Edge handling
nums = list(map(int, input().split()))
target = int(input())

if len(nums) < 2:
    print("Not possible")
else:
    print(two_sum(nums, target))

Handles small input cases safely.

7. Algorithm

1. Iterate through array.

2. Store seen values in a hash map.

3. Check if complement exists.

4. Return indices if found.

8. Common Mistakes

1. Returning values instead of indices when required.

2. Not handling duplicates correctly.

3. Using brute force unnecessarily.

4. Forgetting edge cases.

9. Applications

1. Interview coding problems.

2. Financial data matching.

3. Pair searching problems.

4. Algorithm practice.

Conclusion

The Two Sum problem is a foundational interview question that teaches hashing and optimization techniques.

The hash map approach is the most efficient and widely used solution.