Two Sum Problem - Python Coding Challenges

Two Sum Problem - Python Coding Challenges

🧠 Understanding the Two Sum Problem in Python

When learning Python or preparing for coding interviews, one of the most popular beginner problems on LeetCode is called “Two Sum.

It may seem simple — find two numbers that add up to a target — but it’s also the best way to learn how programmers think logically and optimize code.

Problem Statement

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

You can’t use the same number twice, and you can return the answer in any order.

Example

Input: nums = [3, 5, 7, 11], target = 10
Output: [0, 2]
Explanation: nums[0] + nums[7] = 3 + 7 = 10

Step 1: Brute-Force Approach (Beginner-Friendly)

The Brute Force method involves checking every possible pair of numbers in the list to see if their sum equals the target.

Imagine the numbers are on paper: [2, 7, 11, 15] with target 9.

Check pairs one by one:

  • 3 + 7 = 10 ✅ Done!
  • If the first number didn’t work, pick the next and repeat.

Python Code (Brute Force)


def twoSum_brute_force(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 indices
    return []  # if no solution found

# Example usage
nums = [3, 5, 7, 11]
target = 10
result = twoSum_brute_force(nums, target)
print("Brute-Force Output:", result)

✅ How It Works: 

  •  Loop over all pairs (i, j) where i < j. 
  • Check if nums[i] + nums[j] == target. 
  • Return the pair of indices if found.
Note: Works for small lists but slow for large arrays. Time complexity = O(n²) Space Complexity: O(1)

Why we do this first:

  • It’s the most intuitive approach
  • Easy to understand and visualize
  • You don’t need any extra knowledge (just arrays & loops)

Pros & Cons

  • ✅ Pros: Very simple to implement, Good for beginners to understand the problem
  • ❌ Cons: Slow for large lists, Checks every pair → O(n²) time complexity

Conclusion: Brute Force is chosen first because it builds intuition about the problem.

Step 2: Optimized Approach Using HashMap (Python Dictionary)

This method uses a dictionary to store numbers we've already seen, allowing us to check if the complement (target - current number) exists in constant time.

Instead of checking all pairs, we can remember numbers we have already seen using a dictionary.

Key Idea:

For each number num, calculate the complement:


complement = target - num

Then:

  • If the complement exists in the dictionary → return indices ✅
  • If not → store the current number in the dictionary for future checks ✍️

Step-by-Step Example

Step Current Number Complement Is Complement in Dictionary? Action Dictionary (num → index)
1 3 7 ❌ No Store 2 {2: 0}
2 7 3 ✅ Yes Return [0,2] {3: 0, 7: 1}

Python Code (HashMap / Dictionary)


def twoSum_hashmap(nums, target):
    seen = {}  # dictionary to store number:index
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]  # return indices
        seen[num] = i
    return []  # if no solution found

# Example usage
nums = [3, 5, 7, 11]
target = 10
result = twoSum_hashmap(nums, target)
print("HashMap Output:", result)

🧠 How It Works: 

  • For each number num, calculate complement = target - num. 
  • Check if complement is in seen dictionary. 
  • If yes → return [index of complement, current index]. 
  • Otherwise, store num with its index in the dictionary.
Complexity: Time = O(n), Space = O(n). Much faster than brute-force!

Why we do this:

  • We want a faster solution for large inputs
  • Checking a dictionary (HashMap) is instant, no loops needed for previous numbers

Pros & Cons

  • ✅ Pros: Much faster → O(n) time, Efficient memory usage → stores only numbers needed
  • ❌ Cons: Requires understanding HashMap / dictionary, Slightly more advanced for absolute beginners
Two Sum Problem - Python Coding Challenges Screenshot

Step 3: Real-World Analogy

Imagine shopping with a target budget of ₹9. You keep a note of prices you’ve seen:

  • Pick an item worth ₹2 → note “2 seen.”
  • Next item ₹7 → check note, 2 exists → 2+7=9 ✅ Done!

HashMap in programming works the same way.

Step 4: Summary

Method Concept Time Complexity Space Complexity Notes
Brute Force Try all pairs O(n²) O(1) Easy but slow
HashMap / Dictionary Store previous numbers O(n) O(n) Fast & smart

Conclusion

The Two Sum problem teaches beginner programmers:

  • Start simple with brute-force
  • Identify inefficiency
  • Use data structures (like dictionaries) to optimize
  • Once you understand this pattern, you can solve hundreds of similar problems efficiently!

Task 1 — Return the numbers (Not indices) Easy

Write a function two_sum_numbers(nums, target) that returns a list with the two numbers that sum to target. If no pair exists, return []. Preserve the original numbers as they appear in the array.

# Example
nums = [10, 20, 35, 50, 75, 80]
target = 70
# Expected output: [20, 50]

# Signature
# def two_sum_numbers(nums: list[int], target: int) -> list[int]:
Use a hash map to remember values already seen. When you find a complement, return the pair as the two numbers (not their indices).
Task 2 — Exists? True/False Easy

Create has_pair(nums, target) that returns a boolean: True if any two elements sum to the target, otherwise False. Keep runtime linear.

# Example
nums = [1, 2, 4, 9]
target = 8
# Expected output: False
Scan once and keep seen numbers in a set. If the complement exists, return True immediately; at the end return False.
Task 3 — Count unique pairs Medium

Implement count_unique_pairs(nums, target) which returns how many unique pairs sum to target. A pair is unique by the values it contains — order doesn't matter. Example: (1,5) and (5,1) are the same.

# Example
nums = [1, 5, 7, -1, 5]
target = 6
# Expected output: 2  # pairs -> (1,5) and (7,-1)
Sort-and-two-pointer works, or count frequencies: for each unique value v, check if target-v exists and adjust for duplicates carefully so each pair counts once.
Task 4 — Sorted input: two-pointer indices Easy

Given a sorted list nums, write two_sum_sorted(nums, target) that returns indices of the two numbers (0-based) using the two-pointer technique. Do not allocate extra sets or maps.

# Example
nums = [2, 3, 4]
target = 6
# Expected output: [1, 2]
Set left at 0, right at len(nums)-1; move pointers inward depending on the sum compared to target.
Task 5 — Multiple targets Medium

Write two_sum_many_targets(nums, targets) that returns a dictionary mapping each target to any valid pair of indices (or an empty list if none). Aim for better-than-naive efficiency when there are many targets.

# Example
nums = [2,7,11,15]
targets = [9, 13, 18]
# Expected: {9:[0,1], 13:[0,2], 18:[1,2]}
One approach: build a value->index map once; then for each target scan values and check complements. For many targets, consider precomputing all possible sums of pairs if n is small.
Task 6 — Input validation & user messages Easy

Wrap a robust validator around your two-sum functions. Return clear messages for invalid types, empty lists, or non-integer targets. Function name: validated_two_sum(nums, target).

# Example
nums = []
target = 10
# Expected output: "List is empty. Please provide valid numbers."
Check type and length early. Use descriptive exceptions or return tuples like (success, message_or_result).
Task 7 — Interactive CLI script Easy

Compose a small script run_two_sum_cli.py that prompts the user to enter a comma-separated list of numbers and a target, then prints indices or numbers for a found pair. Keep input parsing defensive.

# Example run
# Enter numbers: 2,7,11,15
# Enter target: 9
# Result: Indices [0, 1]
Use input(), str.split(',') and map(int,...) inside try/except. Reuse your two-sum function for the logic.
Bonus — Three Sum (challenge) Hard

Implement three_sum(nums) that returns all unique triplets that sum to zero. This is an excellent extension of Two Sum ideas (sort + two-pointer inside a loop).

# Example
nums = [-1,0,1,2,-1,-4]
# Expected: [[-1,-1,2], [-1,0,1]]
Sort array first. Loop i over positions, then use two pointers for the remaining subarray while skipping duplicates.

How to use this file: open it in a browser to view the tasks. Copy the snippets into your editor and implement the functions. Hints are hidden by default so you can try first.

📘 Previous Blog: Power of Two in Python — Easy Bit Manipulation Guide

Before diving into backtracking, revisit our detailed guide on Power of Two in Python. Learn how bit manipulation, binary checks, and mathematical logic can efficiently verify if a number is a power of two. Perfect for Python beginners and interview preparation!

🔙 Read Previous: Power of Two in Python
Previous Post Next Post

Contact Form