Leetcode
Two Sum
This is a very basic problem. You need to find two elements in an array that add up to the target.
The easiest idea here is to just iterate through the array two times and checking if both elements add up to the target
function twoSum(nums: number[], target: number): number[] {
for(let i=0;i<nums.length;i++){
for(let j=i+1;j<nums.length;j++){
if(nums[i] + nums[j] == target){
return [i,j]
}
}
}
return []
}This has the following Time and Space Complexity:
Time: O(n^2)
Space: O(1)
But we can sacrifice some space to to reduce the time we need to find a solution
The idea here is to use a hashmap. We calculate the complement of the target t and the current element with index i
function twoSum(nums:number[], target:number): number[]{
const complementMap ={}
for(let i=0;i<nums.length;i++){
const complement = target - nums[i];
if(complementMap[complement] !== undefined){
return [complementMap[complement],i]
}
complementMap[nums[i]] = i
}
return []
}
This results in:
Time: O(n)
Space: O(n)