Two Sum(#1)
Category: Array, Hash Map, Foundation
๐งฉ Problem Statement
Given an array of integers nums and an integer target...
๐ Examples
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation: Because nums[0] + nums[1] == 9.
๐ง Approach
Approach 1: Brute Force
Loop through each element in the array. For every element, subtract it from the target and search the remainder in the rest of the array using another loop. This results in O(n^2) time.
Approach 2: Optimal using Hash Map
Use a hash map to store each element and its index. For each number, check if the complement (target - current number) exists in the map. If it does, return both indices. This gives O(n) time with O(n) space.
๐ป Code
// Approach 1: Brute Force
var twoSum = function(nums, target) {
for (let i = 0; i < nums.length; i++) {
let diff = target - nums[i];
for (let j = i + 1; j < nums.length; j++) {
if (nums[j] === diff) {
return [i, j];
}
}
}
};
// Approach 2: Optimal using Hash Map
var twoSum = function(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);
}
};
๐ Complexity
Time: O(nยฒ)
Space: O(1)