× logo Home HTML CSS Javascript React-App Angular logo
logo

Mastering Top 10 Javascript Algorithms

**Algorithm Name**: Two Sum Problem

* **Questions**:
Find out if the input array is sorted. Do we return the first pair found or all pairs? What should we return if no pair adds up to the target sum?

* **Time Complexity**:
- Brute Force: O(n^2)
- Optimized: O(n)

* **Space Complexity**:
- Brute Force: O(1)
- Optimized: O(n)

* **Approaches**:
- **Brute Force**:
Loop through the array, and for each index, loop through the rest of the array looking for a number that, when added to the current number, equals the target.
This requires two nested loops and thus has a time complexity of O(n^2).

- **Optimized**:
Use a hash table (or an Object in JavaScript) to store the differences between the target and each element in the array.

For each element, if it's present as a key in the hash table, that means we've found a pair that adds up to the target.

This has a time complexity of O(n) because we're passing through the array only once.

* **Explanation**:
The optimized approach exploits the speed of lookups in a hash table (constant time, O(1)).
Instead of having to loop again through the array to find the matching pair, we immediately know if it exists thanks to the hash table.

* **Sample Code**:javascript

const twoSum = (nums, target) => {
const hash = {};

for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (hash[nums[i]] !== undefined) {

return [hash[nums[i]], i];
}
hash[complement] = i;
}
return null;
};


//Unit Test
console.log(twoSum([2, 7, 11, 15], 9)); // Output:[ 0, 1 ]
- Input: nums = [2, 7, 11, 15], target = 9




logo