Two Sum Problem | JavaScript

Two Sum Problem | JavaScript

Here I have given a solution for the 'Two Sum' problem, using JavaScript. If you have any better solution please let me know bellow.

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.

It has a few Constraints:

  • 2 <= nums.length <= 10<sup>4</sup>

  • -10<sup>9</sup> <= nums[i] <= 10<sup>9</sup>

  • -10<sup>9</sup> <= target <= 10<sup>9</sup>

  • Only one valid answer exists.

Solution One:

var twoSum = function (nums, target) {
    // Create a hash map to store numbers and their indices
    const numToIndex = {};

    // Loop through the array, recording indices and checking for complements
    for (let i = 0; i < nums.length; i++) {
        const num = nums[i];
        const complement = target - num;

        // Check if the complement is in the hash map
        if (numToIndex[complement] !== undefined) {
            // If found, return the indices
            return [numToIndex[complement], i];
        }

        // Otherwise, record the index of the current number
        numToIndex[num] = i;
    }
};

Solution Two:

var twoSum = function (nums, target) {
    // Create an array of objects with original index and value
    const indexedNums = nums.map((num, index) => ({ num, index }));

    // Sort the array based on the values
    indexedNums.sort((a, b) => a.num - b.num);

    // Initialize two pointers, one at the beginning and one at the end
    let left = 0;
    let right = indexedNums.length - 1;

    // While pointers don't cross
    while (left < right) {
        const sum = indexedNums[left].num + indexedNums[right].num;

        if (sum === target) {
            // If the sum matches the target, return the original indices
            return [indexedNums[left].index, indexedNums[right].index];
        } else if (sum < target) {
            // If the sum is less than the target, move the left pointer to the right
            left++;
        } else {
            // If the sum is greater than the target, move the right pointer to the left
            right--;
        }
    }
};

Solution Three:

var twoSum = function (nums, target) {
    const numToIndex = new Map();

    for (let i = 0; i < nums.length; i++) {
        const num = nums[i];
        const complement = target - num;

        if (numToIndex.has(complement)) {
            return [numToIndex.get(complement), i];
        }
        numToIndex.set(num, i);
    }
};