
The Two Sum problem in Java
Two Sum problem is the most common question one can come across while preparing for job interviews in developer roles. I'm writing this blog to tell you about the various approaches you can follow to solve this problem in Java, ranging from the easiest to the best approach. The problem You are given a set of numbers in the form of an array and a target sum. You have to find two numbers in this array such that their sum is equal to the given target value. How would you do so? Easiest and Naive Approach: Brute Force (as always!) You iterate over each element of the array(x'th element) and create another loop inside the above loop from (x+1)'th element to the end. In each iteration you check if the sum of current element of outer loop and current element of the inner loop add up to the sum. Easy right? Has the highest complexity though! Code Following is the code for this approach: public static int[] getTargetSumIndices(int[] arr, int target){ for(int i = 0; i < arr.length; i++){ int x =
Continue reading on Dev.to
Opens in a new tab




