Two Sum Problem: Python Solution for LeetCode & Coding Interviews

Two Sum Problem: Python Solution for LeetCode & Coding Interviews

Introduction The Two Sum Problem Python is a staple in coding interviews, especially for those delving into data structures and algorithms. This problem frequently surfaces in platforms like...

Table of Contents

Introduction

The Two Sum Problem Python is a staple in coding interviews, especially for those delving into data structures and algorithms. This problem frequently surfaces in platforms like LeetCode and is a common fixture in FAANG interviews. Understanding the Two Sum problem not only sharpens your problem-solving skills but also prepares you for real-world coding challenges.

Problem Statement

The Two Sum problem is straightforward: Given an array of integers, find two numbers such that they add up to a specific target. Return the indices of the two numbers.

Example: Given nums = [2, 7, 11, 15], target = 9, return [0, 1] because nums[0] + nums[1] = 9.

Brute Force Approach

The simplest way to solve the Two Sum Problem Python is by checking each pair of numbers to see if they sum to the target.

Python Code


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]

This method is intuitive but inefficient, with a time complexity of O(n²) and space complexity of O(1).

Optimized Approach Using Hash Map

To improve efficiency, we use a hash map in Python to store numbers and their indices. This allows us to check if the complement of the current number (difference between target and current number) exists in the map.

Step-by-Step Explanation

  • Initialize an empty hash map.
  • Iterate over the list, checking if the complement exists in the map.
  • If found, return the indices. Otherwise, add the number to the map.

Python Code


def two_sum(nums, target):
    num_map = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in num_map:
            return [num_map[complement], i]
        num_map[num] = i

This approach reduces the time complexity to O(n) with space complexity also at O(n), making it a preferred solution in interviews.

Dry Run Example

Consider nums = [2, 7, 11, 15], target = 9. Initially, num_map is empty. Iterate through nums:

  • i=0, num=2, complement=7. Not in num_map. Add 2:0 to num_map.
  • i=1, num=7, complement=2. Found in num_map. Return [0, 1].

Common Mistakes to Avoid

  • Confusing indices with values.
  • Not handling duplicate values properly.

Interview Tips

When explaining your solution in interviews, clearly articulate your thought process. Discuss the time and space complexity of both approaches. Be ready for follow-up questions like "Can you solve it without using extra space?"

LeetCode Submission Tips

  • Consider edge cases like empty arrays or single-element arrays.
  • Ensure you handle constraints effectively, such as large numbers or negative integers.

Conclusion

The Two Sum Problem Python is an excellent introduction to algorithmic thinking. By practicing problems like this, you build a strong foundation in Python DSA. Keep coding and try more challenges to excel in your coding interviews!

FAQ

What is the Two Sum problem?

It's a problem where you find two numbers in an array that add up to a specific target.

Why is the hash map approach preferred?

It reduces time complexity to O(n), making it more efficient for large datasets.

How do I handle duplicate numbers?

Use a hash map to track indices carefully, ensuring you match numbers correctly.

What if there are multiple solutions?

Return the first pair found, as per the typical problem statement.