leetcode-150

Two Sum

The Two Sum problem is one of the most popular and frequently asked coding interview questions. It evaluates your ability to work with arrays and hash maps efficiently.


๐Ÿ” Problem Statement

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to the 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.


๐Ÿงช Example

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

๐Ÿง  Brute Force Approach

๐Ÿ’ก Idea:

Use two loops to try every pair of elements and check if their sum equals the target.

var twoSum = function(nums, target) {
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] === target) {
                return [i, j];
            }
        }
    }
};

โšก Optimal Approach: Using a Hash Map

๐Ÿ’ก Idea:

Use a hash map to store the value-to-index mapping of each number as you iterate. For every element num, check if target - num exists in the map.

โœ… JavaScript Code:

var twoSum = function(nums, target) {
    const map = new Map(); // value -> index

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

        if (map.has(complement)) {
            return [map.get(complement), i];
        }

        map.set(nums[i], i);
    }

    return []; // fallback, though the problem guarantees one solution
};

๐Ÿ•’ Complexity Analysis

Metric Value
Time Complexity O(n)
Space Complexity O(n)

๐Ÿ” Step-by-Step Example

Input: nums = [3, 2, 4], target = 6


๐Ÿงท Edge Cases


๐Ÿ† Best Practices


๐Ÿ”— Reference

LeetCode: Two Sum