Explorer
JavaScript

Write a function `twoSum(nums, target)` that returns indices of two numbers that add up to the target.

Problem Statement

<p>Write a function <code>twoSum(nums, target)</code> that returns indices of two numbers that add up to the target.</p>

Examples

Input: nums = [2, 7, 11, 15], target = 9

Output: [0, 1]

Explanation: nums[0] + nums[1] === 9.

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

Output: [1, 2]

Explanation: nums[1] + nums[2] === 6.

Complexity

Time Complexity: O(N)

Space Complexity: O(N)

Hints

💡 Hint 1: A brute force approach uses two nested loops — O(n²). 💡 Hint 2: For O(n), use a Map to store each number and its index. 💡 Hint 3: For each number, check if target - number exists in the Map.

Editorial & Approach

Problem Overview & Intuition

To solve Two Sum, we consider the execution characteristics of JavaScript engines. Write a function `twoSum(nums, target)` that returns indices of two numbers that add up to the target. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.

Step-by-Step Approach

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (a brute force approach uses two nested loops — o(n²)).
  3. Implement Logic: Handle state and transformations efficiently (for o(n), use a map to store each number and its index).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function twoSum(nums, target) {
  const map = new Map();
  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 [];
}

Complexity Analysis

Time Complexity O(N) single pass hash map lookup
Space Complexity O(N) hash map storage

Edge Cases & Corner Traps Handled

  • Empty or boundary inputs (empty arrays, strings, zero length).
  • Type checks and unexpected values (e.g. null, undefined, negative numbers).
  • Closure preservation and memory isolation between separate invocations.

Two Sum

Medium

Write a function twoSum(nums, target) that returns indices of two numbers that add up to the target.

Example Scenarios
1Example 1
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation:

nums[0] + nums[1] === 9.

2Example 2
Input: nums = [3, 2, 4], target = 6
Output: [1, 2]
Explanation:

nums[1] + nums[2] === 6.

Editor
Loading Editor...
nums =
[2, 7, 11, 15]
target =
9
Output:Click "Run" above to execute and verify your code here.
[0,1]