Leetcode: Two Sum
Leetcode — Two Sum
Leetcode categorizes “Two Sum” as an easy question. In this problem, you must return the indexes of two numbers that add up to the given target number. Two Sum - LeetCode
You can solve this in a brute force way using two for loops to check each number against every other number ( 0(n²) ). We can also solve this using two-pointers and using an approach similar to a binary search. I am going to walk through one of the most common solutions for this problem.
Steps:
-
Create a HashMap to hold each number and its index as the value.
-
Loop through the nums array.
-
For each iteration in the for loop, we can subtract the current number from the target number and try to find that number in the map. If the number exists, return the current index and that number's index (from the map). If that number doesn’t exist in the map, add it to the map along with its index.
-
If there are no numbers that sum up to the target, return an array of -1s.
Kotlin Solution: {% gist https://gist.github.com/cmcoffeedev/677c1c4240dfcdc8af24ede03ea54b4f.js %}