<AI/>
enru
All posts

Two sum

LeetCode 1: Find the indices of two numbers in an array that add up to the target in a single pass with a hash map.

Difficulty
Easy
Published
Topics
#array#hash table
Open on LeetCode

Problem Description

You are given an integer array nums. Write a function twoSum that finds two numbers in the array whose sum equals the target number target. The function should return an array with the indices of the elements that satisfy the condition. The order of the indices in the answer doesn't matter.

Constraints

  • The array contains from 2 to 104 unique values
  • Values are in the range from -109 to 109
  • target is in the range from -109 to 109
  • There is always exactly one solution

Examples

Input

nums = [2, 7, 11, 15]
target = 9

Answer: [0, 1] or [1, 0]

The sum of 2 and 7 is 9, so index1 = 0 and index2 = 1. We return [0, 1].

Solution

To solve this problem efficiently, we need a way to get the index of a number in the array without scanning it. A Hash Map (or its equivalents) helps here, since it lets us get a value by key in constant time.

We start with an empty map where the key is a number and the value is its index in the array. Then we loop over all elements of the array and perform the following steps on each iteration.

  1. Compute the difference between target and the current number. This is the second number we're looking for.
  2. To check whether that number is in the array, we look it up in our map. If the map has it, we've already seen it earlier in the array and can get its index. We've found the pair and can return their indices as an array.
  3. If the map doesn't have it, we add the current number to the map, using the number as the key and its index as the value.
typescript
export const twoSum = (nums: number[], target: number): number[] => {
  // Create an object to track the indices of numbers from the array
  // You could also use new Map(), but a plain object does exactly the same and is a bit simpler to work with.
  const indexMap: Record<number, number> = {};
 
  for (let i = 0; i < nums.length; i++) {
    // Compute the second number we need
    const complement = target - nums[i];
 
    // Check whether the object has an index for this number
    const secondIndex = indexMap[complement];
 
    // If the index is already in the object, we have found the pair
    if (secondIndex > -1) {
      return [i, secondIndex];
    }
 
    // Otherwise, store the index of the current number in the object
    indexMap[nums[i]] = i;
  }
 
  return [];
};

Complexity Analysis

n is the number of elements in the array.

Time Complexity

O(n), since we iterate over all elements of the array.

Space Complexity

O(n), since we add up to n elements to the map.