Feature image

Two Sum – Leetcode Solution using JavaScript

Hello everyone. In this post, I am going to solve Two Sum problem from leetcode. This problem is related to arrays and hashing.

In this problem, given a target value, we have to find out the indices of the two numbers such that they add up to target. So for example if the array is [2,7,11,15] and the target is 9, then we have to return the index value [0,1]. Because the index value of 0 and 1 is 2 and 7. the addition of 2 and 7 is 9.

I solved the problem using JavaScript and I went with the straight forward way to solve it. It passed the submission! That’s why I did not think about any optimization or any other solution.

To solve this problem, I created a loop and inside that loop I created an inner loop. Basically checking every combination until I get a match. I do not think I need to explain any thing for this code. Please take a look at it and if you have any problem understanding please comment on the post. I will try my best to explain.

Solution

Two Sum Solution using JavaScript
Two Sum Solution

Hello readers, If you are like me who wants to get better at coding, please check out my other blog posts where I solve other leetcode problems.

In the next post, I am going to solve Valid palindrome. Although It is similar to Valid Anagram, if you face trouble check out my solution. There are a few slight changes in the condition.

If you like my solution, please check out my other post about various leetcode solutions. If you want me to solve any other leetcode problem, feel free to comment it below.

3 thoughts on “Two Sum – Leetcode Solution using JavaScript”

  1. Pingback: Valid Palindrome - Leetcode | TypeScript Solution | Al Fahim

  2. Pingback: Best Time to Buy and Sell Stock | Typescript Solution | Al Fahim

  3. Pingback: Valid Parentheses | TypeScript Solution | Al Fahim

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.