Skip to content

Commit

Permalink
Raza khan9639 (#56)
Browse files Browse the repository at this point in the history
* Hactoberfest Contribution Problem#13

* Hactoberfest Contribution Problem#13

* Hacktoberfest Contribution Problem #12

* Problem #9 Javascript

* LeetCode Problem #984

* LeetCode Javascript Problem #1
  • Loading branch information
RazaKhan9639 authored Oct 12, 2022
1 parent c5a984c commit ae5d76d
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions JS/TwoSum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//Name: Raza Mohayyuddin

//Username: RazaKhan9639

//Approach: First create a empty array named sum. After that create map to store elements of array subtracted by target as keys and its indices as values after looping through array. After that loop through the array again and if difference varaibale is in the hashmap then store the current index value in sum array and its associated index value in sum array.

var twoSum = function (nums, target) {
sum = [];
// Map to store the difference and its index
index_map = new Map();
// Loop for each element in the array
for (let i = 0; i < nums.length; i++) {
let difference = target - nums[i];
if (index_map.has(difference)) {
sum[0] = i;
sum[1] = index_map.get(difference);
break;
} else {
index_map.set(nums[i], i);
}
}
return sum;
};

0 comments on commit ae5d76d

Please sign in to comment.