Write a function `twoSum(nums, target)` that returns indices of two numbers that add up to the target.
Problem Statement
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
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
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (a brute force approach uses two nested loops — o(n²)).
- Implement Logic: Handle state and transformations efficiently (for o(n), use a map to store each number and its index).
- 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
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.