You are given an array of integers nums
and an integer target
.
Return the indices of the two numbers such that they add up to the target.
Rules:
var twoSum = function(nums, target) {
for (let x = 0; x < nums.length; x++) {
for (let i = x + 1; i < nums.length; i++) {
if (nums[x] + nums[i] === target) {
return [x, i];
}
}
}
}
1. Time Complexity = O(n²): You’re using two nested loops:
That means:
This approach does not scale well for large arrays.
2. Inefficient for Real-World Data: When working with larger datasets (thousands or millions of entries), this approach becomes computationally expensive and slows down execution dramatically.
Instead of checking every pair (which is O(n²)), we use a HashMap to store numbers as we iterate.
For each element, we check if its complement (target - nums[i]
) already exists in the map.
If it does, we’ve found our pair!
If not, we store the current number and its index in the map.
Map()
.nums[i]
:
complement = target - nums[i]
.map
already has this complement
, return [map.get(complement), i]
.map.set(nums[i], i)
. [0, 1]
i | nums(i) | complement | map (before) | Action |
---|---|---|---|---|
0 | 2 | 7 | {} | Store (2 → 0) |
1 | 7 | 2 | {2: 0} | Found! return 0, 1 |
function twoSum(nums, target) {
// Initialize an empty Map()
const map = new Map(); // stores {num: index}
// Loop through each element nums[i]
for (let i = 0; i < nums.length; i++) {
// Compute complement = target - nums[i]
const complement = target - nums[i];
// map already has this complement
if (map.has(complement)) {
return [map.get(complement), i];
}
// store the current number with its index
map.set(nums[i], i);
}
return []; // no valid pair (shouldn’t happen as per problem)
}
console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1]
Approach | Code Style | Time Complexity | Space | Suitable For |
---|---|---|---|---|
Brute Force | Two loops | O(n²) | O(1) | Small input sizes |
Optimized (HashMap) | Single loop | O(n) | O(n) | Large inputs / production use |
Using a HashMap allows constant-time lookups for the complement, reducing complexity from O(n²) → O(n) — a must-know trick for interviews.
"Each input would have exactly one solution, and you may not use the same element twice." That means:
I'm Rahul, Sr. Software Engineer (SDE II) and passionate content creator. Sharing my expertise in software development to assist learners.
More about me