Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Is there any more efficient way to code this "2 Sum" Questions 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.
Brute Force Approach - O(n²)
The naive approach uses nested loops to check every pair of elements:
const bruteForceTwoSum = (arr, target) => {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] === target) {
return [i, j];
}
}
}
return [];
};
const arr = [2, 5, 7, 8, 1, 3];
console.log("Brute force result:", bruteForceTwoSum(arr, 10));
Brute force result: [ 2, 5 ]
Optimized HashMap Approach - O(n)
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 adds up to the target. If there are any, we will return an array containing their indices.
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] !== undefined){
return [map[el], i];
}
map[arr[i]] = i;
}
return [];
};
console.log(twoSum(arr, 10));
console.log(twoSum(arr, 12));
console.log(twoSum(arr, 13));
console.log(twoSum(arr, 14));
console.log(twoSum(arr, 24));
[ 2, 5 ] [ 1, 2 ] [ 1, 3 ] [ 3, 6 ] []
How the HashMap Approach Works
1. Create an empty map to store values and their indices
2. For each element, calculate the complement (target - current element)
3. Check if the complement exists in the map
4. If found, return the indices; otherwise, store the current element and continue
5. Return empty array if no pair is found
Comparison
| Approach | Time Complexity | Space Complexity | Efficiency |
|---|---|---|---|
| Brute Force | O(n²) | O(1) | Slow for large arrays |
| HashMap | O(n) | O(n) | Optimal for most cases |
Key Points
? The HashMap approach trades space for time complexity
? Use `map[el] !== undefined` instead of `map[el]` to handle zero values correctly
? The function returns indices, not the actual values
? Only one solution is returned even if multiple pairs exist
Conclusion
The HashMap approach provides the most efficient solution with O(n) time complexity. It's significantly faster than the brute force method for large datasets while using reasonable extra space.
