
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Efficient Solutions for 2 Sum Questions in JavaScript
Our job is to write a function that solves the two-sum problem in at most linear time.
Two Sum Problem
Given an array of integers, we have to find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers that add up to the target, and if no two elements add up to the target, our function should return an empty array.
Solving the problem in O(n) time
We will use a hashmap to keep a record of the items already appeared, on each pass we will check whether there exists any element in the map which when added to the current element add up to the target, if there are any we will return an array containing their indices and if we go through the whole loop without satisfying this condition, we will return an empty array.
Example
const arr = [2, 5, 7, 8, 1, 3, 6, 9, 4]; const sum = 10; const twoSum = (arr, sum) => { const map = {}; for(let i = 0; i < arr.length; i++){ const el = sum - arr[i]; if(map[el]){ return [map[el], i]; }; map[arr[i]] = i; }; return []; }; console.log(twoSum(arr, sum)); console.log(twoSum(arr, 12)); console.log(twoSum(arr, 13)); console.log(twoSum(arr, 14)); console.log(twoSum(arr, 24));
Output
The output in the console will be −
[ 2, 5 ] [ 1, 2 ] [ 1, 3 ] [ 3, 6 ] []