Solutions for LeetCode “Two Sum” problem in Java

Leetcode Problem:-

Let’s start understand the problem,

Here, we have to find the indices of two numbers from given array in which sum of that two number should be equal to target number that given in function argument.

Here, I thought, easiest solution is we have to just find numbers whose sum is equal to target number. So, first idea click on my brain is:

target number = first number + second number

but here problem is that numbers could be from any indices. So, second idea strike to my brain is:

target number = array[i] + array[j]

Here, my simple logic is if we got i == j(same value) then simply break that loop. And rest element should be go as per our logic(target = array[i]+array[j]) and return two indices that match our logic.

But, here problem is the complexity of this program is O(n²).We need to reduced that complexity.

So, I used Hashmap to reduce the complexity.

Here is the performance of second code.

Hit here one clap if you like my solving approach and solution.

Thanks for your patiently read !!!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Akash Tawade

I am enthusiastic senior software developer , I am working on java as well as latest DevOps technologies. My hobbies are reading books and making memes.