Back to articles
Two Sum with an Optimized Solution

Two Sum with an Optimized Solution

via Dev.tokittichanr

Coming back from my previous article: two sum problem I mentioned that I would show another solution to reduce time complexity. In the previous approach, I used two nested loops to check every possible pair of numbers in the array. This is essentially a brute-force method, where we try all combinations to find two numbers that add up to the target. In this article, we will use a different approach. Instead of checking every pair, we use a hash map (object in JavaScript) to reduce the number of steps needed to find the solution. Let’s take a look. Question Given an array of integers nums and an integer target , return the indices of the two numbers such that they add up to target . You may assume that each input has exactly one solution , and you may not use the same element twice. You can return the answer in any order. Example Input: nums = [2,11,15,7], target = 9 Output: [0,3] Explanation: Because nums[0] + nums[3] == 9, we return [0, 3]. Solution function twoSum ( nums , target ) {

Continue reading on Dev.to

Opens in a new tab

Read Full Article
3 views

Related Articles