# LeetCode: Two Sum Solution

Classical hash table problem

## Approach: Hash table

Use hash table to reduce the query time complexity for

target - num

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var twoSum = function (nums, target) {2  const elLastIdxMap = nums.reduce(3    (acc, el, idx) => acc.set(el, idx),4    new Map()5  )6
7  for (const [idx, num] of nums.entries()) {8    const rest = target - num9    if (elLastIdxMap.has(rest) && elLastIdxMap.get(rest) !== idx) {10      return [idx, elLastIdxMap.get(rest)]11    }12  }13}```

Original problem

## Similar problems

3Sum

4Sum

Two Sum II - Input Array Is Sorted

Two Sum III - Data structure design

Subarray Sum Equals K

Two Sum IV - Input is a BST

Two Sum Less Than K

Max Number of K-Sum Pairs

Count Good Meals

Count Number of Pairs With Absolute Difference K

Number of Pairs of Strings With Concatenation Equal to Target

Find All K-Distant Indices in an Array

First Letter to Appear Twice

Number of Excellent Pairs

Number of Arithmetic Triplets

Node With Highest Edge Score

Check Distances Between Same Letters

Find Subarrays With Equal Sum

Largest Positive Integer That Exists With Its Negative

Number of Distinct Averages

leetcode

neetcode

array

hash table

## Next Post

LeetCode: Climbing Stairs

Feb 6, 2021

Memoized recursion

Search Posts