← Back to libraryQuestion 157 of 468
🧩JavaScript CodingIntermediate

Two Sum

📌 Definition:

Given an array of numbers and a target, return the indices of the two numbers that add up to the target.

📖 Detailed Explanation:

Brute force is O(n^2). The optimal solution is a single pass with a hash map: for each number, check whether target - number was already seen; if so, return the stored index and the current index.

💻 Solutions:
function twoSum(nums, target) {
  const seen = new Map(); // value -> index
  for (let i = 0; i < nums.length; i++) {
    const need = target - nums[i];
    if (seen.has(need)) return [seen.get(need), i];
    seen.set(nums[i], i);
  }
  return [];
}
🔑 Key Points:
  • Hash map turns O(n^2) into O(n)
  • Store value → index as you go
  • Check complement BEFORE inserting current (avoids using an element twice)
  • Handles duplicates correctly
🌍 Real-World Example:

The complement-in-a-hashmap pattern is the most reused technique in coding interviews and appears in pair-matching, deduplication, and cache-hit logic.

🎯 Scenario-Based Interview Question:

A candidate inserts nums[i] into the map BEFORE checking for the complement. What bug does that cause for target = 6, nums = [3, ...]?