Two Sum - Leetcode Solution


Step-by-Step Thought Process

Brute Force

  1. Understand the problem: Find two numbers in an array that sum to a target value and return their indices.
  2. Get the length n of the input array nums.
  3. Iterate through each index i from 0 to n-1 using a loop.
  4. For each i, iterate through each index j from i+1 to n-1 using a nested loop.
  5. Check if nums[i] + nums[j] equals the target.
  6. If true, return a tuple or list containing indices i and j.

Code Solution (Brute Force)


                

                

                

                

Why the Brute-Force Solution is Inefficient

The brute-force solution checks every possible pair of numbers, leading to:

Optimal Solution

The optimal solution uses a hash map to achieve O(n) time complexity:

  1. Initialize an empty hash map to store numbers and their indices.
  2. Iterate through the array with index i from 0 to length-1.
  3. For each number nums[i], compute the complement y as target minus nums[i].
  4. Check if y exists in the hash map and its index is not i.
  5. If found, return a list containing i and the index of y from the hash map.
  6. Otherwise, add nums[i] and its index i to the hash map.

Code Solution (Optimal)


                

                

                

                

Detailed Explanation

Understanding the Problem: Two Sum

The “Two Sum” problem is one of the most well-known algorithmic challenges. Given an array of integers nums and an integer target, the task is to find the indices of two distinct numbers in nums such that they add up to target.

For example:

  • nums = [2, 7, 11, 15], target = 9 → Output: [0, 1] because 2 + 7 = 9.
  • nums = [3, 2, 4], target = 6 → Output: [1, 2]

Why This Problem Matters

Two Sum introduces fundamental concepts in problem solving: iteration, complement computation, and the power of hash maps for constant-time lookup. It also forms the basis for more complex variations like Three Sum, Four Sum, and problems involving pairs with constraints.

Brute Force Approach

The most straightforward solution is to use two nested loops to check every pair of numbers. For each element nums[i], we scan the remaining elements to find if any nums[j] satisfies nums[i] + nums[j] == target.

While easy to implement, this method performs poorly on large arrays due to its quadratic time complexity.

Brute Force Steps:

  1. Loop i from 0 to n - 1.
  2. Loop j from i + 1 to n - 1.
  3. If nums[i] + nums[j] == target, return [i, j].
  4. If no such pair is found, return an empty list or null.

Optimal Solution: Hash Map for Complements

A more efficient solution uses a hash map to store previously seen numbers and their indices. As we iterate through the array, we calculate the complement target - nums[i] and check if it's already in the map. If it is, we return the current index and the stored index of the complement.

Hash Map Steps:

  1. Initialize an empty map seen = {}.
  2. Loop over the array with index i and value num.
  3. Compute complement = target - num.
  4. If complement exists in seen, return [seen[complement], i].
  5. Otherwise, store seen[num] = i.

Example Walkthrough

Input: nums = [3, 2, 4], target = 6
Iteration:

  • i = 0, num = 3 → complement = 3 → not in seen → store {3: 0}
  • i = 1, num = 2 → complement = 4 → not in seen → store {2: 1}
  • i = 2, num = 4 → complement = 2 → 2 is in seen → return [1, 2]

Time and Space Complexity

Time Complexity: O(n), where n is the length of the array. We loop through the array once, and hash map lookups and inserts are constant time.
Space Complexity: O(n), for storing up to n elements in the map.

Edge Cases to Consider

  • Exactly two numbers → trivial case
  • Multiple valid pairs → usually return the first one found
  • No valid pair → return [] or throw an error depending on the implementation
  • Negative numbers and zero → ensure complements are correctly computed

Conclusion

The “Two Sum” problem is a great introduction to using hash maps to speed up lookups and eliminate redundant comparisons. Understanding this approach is key to tackling more advanced problems involving combinations, subsets, or real-time aggregation.

Get Personalized Support at AlgoMap Bootcamp 💡