Code Logo

Two Sum

Published at23 Jul 2026
Easy 1 views
Like0

You are given an array of integers and a target integer. Find two numbers in the array that add up to the target. Return the indices of these two numbers. You may assume that exactly one solution exists, and you may not use the same element twice. The answer can be returned in any order.

The brute force approach uses two nested loops to check every pair, running in O(n²). A hash map solves it in O(n) time: iterate through the array, for each element calculate the complement (target minus current value). If the complement exists in the hash map, return the current index and the complement's index. Otherwise, store the current value and its index in the hash map.

This is the most well-known hash table problem and appears in almost every coding interview.

Edge cases include negative numbers, zero, and duplicate values. The hash map approach handles all of these correctly because it stores the first occurrence of each value, ensuring that each element is used at most once.

Example Input & Output

Example 1
Input
nums=[3,2,4], target=6
Output
[1,2]
Explanation

2+4=6

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

2+7=9

Example 3
Input
nums=[3,3], target=6
Output
[0,1]
Explanation

3+3=6

Algorithm Flow

Recommendation Algorithm Flow for Two Sum

Solution Approach

Use a hash set to track numbers seen so far. For each element, check if the complement (target - current) exists in the set. If it does, return true. Otherwise, add the current element to the set and continue.

function twoSum(nums, target) {
  var seen = {};
  for (var i = 0; i < nums.length; i++) {
    var complement = target - nums[i];
    if (seen[complement] !== undefined) return true;
    seen[nums[i]] = true;
  }
  return false;
}

The complement approach works because if a + b = target, then b = target - a. By storing previously seen numbers in a hash set, we can check if the required complement has already been encountered in O(1) time per element.

Time complexity is O(n), space complexity is O(n) for the hash set.

Best Answers

java
import java.util.*;
class Solution {
    public int[] solution(int[] nums, int target) {
        Map<Integer,Integer> seen = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int comp = target - nums[i];
            if (seen.containsKey(comp)) return new int[]{seen.get(comp), i};
            seen.put(nums[i], i);
        }
        return new int[]{};
    }
}