🧩 What is the Two Sum Problem?

The Two Sum Problem is a classic Data Structures and Algorithms question you’ll see in coding interviews.

Find two different numbers in the array that add up exactly to the target number, and return their positions (indices).

Example:

Array:  [2, 7, 11, 15]  
Target: 9  
Answer: [0, 1]  // Because 2 + 7 = 9

In this example:

📜 Problem Statement in Java

When solving the problem in Java, we usually write it as:

public int[] twoSum(int[] nums, int target)

Where:

🐌 Brute Force Approach

What is Brute Force?

Brute force means trying every possible combination until you find the answer. It’s like checking every pair of shoes in a shop until you find the perfect match.

How It Works for Two Sum:

  1. Start at the first number in the array.
  2. Pair it with every other number that comes after it.
  3. Check if their sum equals the target.
  4. If yes - return their positions (indices).
  5. If no - move to the next number and repeat.

Why It’s Simple but Slow:

Time and Space Complexity:

Example Brute Force:

public int[] twoSumBruteForce(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] == target) {
                return new int[] { i, j };
            }
        }
    }
    return new int[] {}; // If no solution found
}

⚡ Optimal Solution Using Hash Map

What is a Hash Map?

A hash map is like a smart dictionary where:

You can look up any key instantly, without searching through everything.

How It Works for Two Sum:

complement = target - currentNumber

Why It’s Fast:

Time and Space Complexity:

Example Optimal Solution:

import java.util.*;

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    return new int[] {}; // If no solution found
}

🧠 Why Interviewers Ask the Two Sum Question

📚 Summary

The brute force approach checks all possible pairs and is easy to understand, but it’s slow for large arrays. The optimal solution uses a hash map to solve the problem in a single pass, making it much faster. By learning this problem, you not only understand arrays and hash maps better but also prepare yourself for more advanced problems in coding interviews.