Code Logo

Two Sum

Published at23 Jul 2026
Easy 0 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
Recommendation Algorithm Flow for Two Sum

Solution Approach

Create a hash map value -> index. Iterate, compute complement. If complement in map, return [map[complement], i]. Store current value and index.

function solution(nums, target) {
  var map = {};
  for (var i = 0; i < nums.length; i++) {
    var complement = target - nums[i];
    if (complement in map) return [map[complement], i];
    map[nums[i]] = i;
  }
  return [];
}

Time O(n), Space O(n).

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[]{};
    }
}