# LeetCode: Two Sum Solution

*Classical hash table problem*

## Approach: Hash table

Use hash table to reduce the query time complexity for

## Implementation

1var twoSum = function (nums, target) {2 const elLastIdxMap = nums.reduce(3 (acc, el, idx) => acc.set(el, idx),4 new Map()5 )67 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}

## References

## 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

## Comments

Loading comments...

## Tags

leetcode

neetcode

array

hash table

## Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

**Fact corner:** Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

**Still hesitate?** Read HoningJS author's guide on dealing with Toptal interview process.

## Next Post

## Previous Post

Feb 5, 2021