Solving ‘Two Sum’ LeetCode Problem

Jake Borromeo
2 min readDec 31, 2022

--

Photo by Chris Ried on Unsplash

Are you feeling stuck on the Two Sum Leetcode problem? Don’t worry, we’ve all been there. But fear not, for I am here to guide you through the solution and make the journey as enjoyable as possible.

First things first, let’s go over the problem statement:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Got it? Great! Now let’s break down the problem and see how we can solve it.

One way to solve this problem is to use a brute force approach, where we loop through the array and check every combination of numbers to see if they add up to the target. However, this would result in a time complexity of O(n²), which is not ideal for larger arrays.

Instead, we can use a more efficient approach that has a time complexity of O(n). To do this, we can use a hash map to store the numbers we’ve seen so far. As we loop through the array, we can check if the target minus the current number is in the map. If it is, we’ve found our solution.

Here’s the code for this solution:

Copy code
function twoSum(nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
if (map.has(target - nums[i])) {
return [map.get(target - nums[i]), i];
}
map.set(nums[i], i);
}
return [];
}

In this code, we create a new Map object and store it in the map variable. Then, we loop through the nums array and check if the target minus the current number is in the map. If it is, we return the indices of the two numbers that add up to the target. If not, we add the current number to the map with its index as the value.

By using this approach, we are able to solve the Two Sum problem in O(n) time, which is much more efficient than the O(n²) brute force approach.

And there you have it! A solution to the Two Sum problem that is both efficient and easy to understand.

Now, go forth and conquer Leetcode! And remember, with a little bit of humor and a positive attitude, any problem can be solved. Happy coding!

--

--

No responses yet