How to use Hash Map In Javascript
You can optimize the solution using a hash map (JavaScript object) to store the elements and their indices. While iterating through the array, check if the difference between the target and the current element exists in the hash map.
Example: Implementation of hashmap approach to check whether a pair with a given sum exists in an array.
function hasTwoSum(nums, target) {
let numMap = {};
for (let i = 0; i < nums.length; i++) {
let required = target - nums[i];
if (numMap[required]) {
return true;
}
numMap[nums[i]] = true;
}
return false;
}
// Test
let nums = [4, 9, 3, 2, 7];
let target = 11;
console.log(hasTwoSum(nums, target));
Output
true
Time Complexity: O(n) – single pass through the array.
Space Complexity: O(n) – hashmap to store elements.
Check if Pair with Given Sum Exists in Array in JavaScript
Two Sum is a classic algorithmic problem where you’re given an array of integers and a target sum. The task is to determine whether any two numbers in the array add up to the target sum.
Given an array A[] of n numbers and another number x, the task is to check whether or not there exist two elements in A[] whose sum is exactly x.
Examples:
Input: arr[] = [0, -1, 2, -3, 1], x= -2
Output: Yes
Explanation: If we calculate the sum of the output,1 + (-3) = -2
Input: arr[] = [1, -2, 1, 0, 5], x = 0
Output: No
Table of Content
- Brute Force Approach
- Using Sorting + Two Pointers
- Using Hash Map