1. Two Sum
Solved at: Jul 16, 2025 🇲🇽
var twoSum = function (nums, target) {
let mp = new Map();
const length = nums.length;
let i = 0;
while (i <= length) {
const ans = target - nums[i];
if (mp.has(ans)) {
return [mp.get(ans), i]
} else {
mp.set(nums[i], i)
}
i++;
}
return []
};
var twoSum = function (nums, target) {
let mp = new Map(); // Create a Map to store numbers and their indices
const length = nums.length;
let i = 0;
while (i <= length) {
const ans = target - nums[i]; // Calculate the complement needed to reach the target
if (mp.has(ans)) { // Check if the complement exists in the Map
return [mp.get(ans), i] // If found, return the indices of the complement and current number
} else {
mp.set(nums[i], i) // Otherwise, store the current number and its index in the Map
}
i++;
}
// If no solution is found, return an empty array
return []
};