Hashing Method
A more effective method stores the array’s items and their indexes in a hash table (or dictionary). This makes constant-time lookups possible. As the method loops across the array, it determines each element’s complement (goal sum minus the current element) and verifies that it is present in the hash table. If it is located, it provides the indices of the element that is now active as well as its complement; this has an O(n) time complexity.
Below steps to implement above approach
- Create an map objects to store numbers
- Traverse the array using loop
- For each number in the array , find the difference between target value and number.
- If map contains the difference between target value and number then returns true.
- Else returns false.
Example: This example implements the above-mentioned approach.
Javascript
function twoSum(n, arr, target) { const map = new Map(); for (let i = 0; i < n; i++) { const num = arr[i]; const moreNeeded = target - num; if (map.has(moreNeeded)) { return "True" ; } map.set(num, i); } return "False" ; } function main() { const n = 5; const arr = [3, 6, 4, 8, 7]; const target = 10; const ans = twoSum(n, arr, target); console.log(ans); } main(); |
Output
True
Check if Pair with given Sum Exists in Array using JavaScript
We will check if a pair with a given Sum exists in an Array or not using JavaScript.
Contact Us