Algo-Sim › Arrays & Hashing

Two Sum

Easy · Arrays & Hashing · step through it in Java, Python and C++ on your own input

Return the indices of the two numbers that add up to the target, in one pass with a hash map.

Problem

Given an integer array nums and an integer target, return the indices of the two different elements whose values add up to target. Exactly one such pair exists, and you may not use the same element twice. The indices can be returned in any order.

Constraints

Edge cases to test

Follow-up questions

What if the array is already sorted?
Two pointers from both ends, moving the side that makes the sum too small or too big: O(n) time, O(1) space (LC 167).
What if you must return every pair, or there may be none?
Keep counts in the map and emit a pair for each earlier match; return an empty result when no lookup hits. Still O(n) plus the output size.
What if memory is tight?
If you only need the values (not the original indices) and may reorder the array, sort it in place and use two pointers: O(n log n) time, O(1) extra space.

Solution

Java

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> seen = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int need = target - nums[i];
        if (seen.containsKey(need)) {
            return new int[] { seen.get(need), i };
        }
        seen.put(nums[i], i);
    }
    return new int[] { -1, -1 };
}

Python

def two_sum(nums, target):
    seen = {}
    for i in range(len(nums)):
        need = target - nums[i]
        if need in seen:
            return [seen[need], i]
        seen[nums[i]] = i
    return [-1, -1]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> twoSum(vector<int> &nums, int target) {
        unordered_map<int, int> seen = {};
        for (int i = 0; i < int(nums.size()); i++) {
            int need = target - nums[i];
            if (seen.count(need)) {
                return vector<int>{seen[need], i};
            }
            seen[nums[i]] = i;
        }
        return vector<int>{-1, -1};
    }
};

More Arrays & Hashing problems