LeetCode #1 – Two Sum

This is the very first question that I shall be tackling:

This question, as it can be seen, is quite simple. Given the array nums, and integer target, the easiest way to solve this problem should be pretty apparent, and that is to just check every combination of indices until you have a sum that adds to target, and that is exactly what I did:

Note: I made the int j = i +1, and not just 0, because j and i cannot be the same

When I ran this method, it indeed gave the expected result:

However, I realized that, while my code works, in the worst case(meaning that the 2 numbers are the last 2 numbers to be checked), the way I did it is very inefficient, with a time complexity of O(n2). This is most likely why there is a follow up to this question:

This follow-up is also not too difficult either, however more in-depth knowledge of Java is required. There are still a few ways to solve this follow-up. One of them would be to use a Map, which will store the array as keys and the indices of the array as the values associated with them. Each time through the loop, the code will also check to see if the complement has been added to the HashMap. If it does, it will immediately return a new array of the indices. This way, the worst case for this way will only have a time complexity of O(n). The method is displayed here:

Results:

That is all from me for now. I hope you guys at least learned something today, and that you all have a great day!

By:

Posted in:


Leave a comment