PROBLEM:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

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

You can return the answer in any order.

SOLUTION:

Brute force method:

The brute force solution is pretty self-explanatory. I created a nested loop that loops from 0 to the length of the input array. If i is the same as j, it will continue onto the next iteration. If nums[i] + nums[j] == target, we have our two indexes! From here, we return an array of [i, j].

More efficient solution using Python dictionaries:

The second solution using dictionaries is slightly more complex. The first thing we do is construct an empty dictionary. Next, we assign each element in the array to a key and each index to a value. An input array of [16, 24, 9] would result in a map of {16: 0, 24: 1, 9: 2}. We loop from 0 to len(nums) once more and assign complement to our input target subtracted by nums[i]. This is basically just a different algebra form from my brute force a + b = target. Instead, we have b = target - a. Complement is the number that we search the dictionary for. When complement is added to nums[i] we should get the target. In the conditional statement, we check if the complement is in the dictionary and that the value of the complement key is not equal to i (since we can’t use the same element more than once).

This problem took me a while to figure out. At first, I could only solve using the brute-force method. After some hints, I was able to get the dictionary method working. First LeetCode problem… DONE ✅.

More from Soren Rood

I like to make things. sorenrood.com/links.html