The Road Map to Two Sum in Java!! Let's Dive Deep!!

Norbert Seals
Strategio
Published in
3 min readFeb 6, 2023

Well hello there! We are well aware that Data Structures and Algorithms (DSA) are important when it comes to technical interviews! My goal today will be to explain the concepts of how to solve the popular Two Sum DSA problem in Java! I will make sure to break down the steps and come up with a solution!

int[] twoSum(int[] numbers, int target)

Let's start with the arguments inside the parameters. We have our variable numbers, which contain an array of numbers. Next, we have our target which holds a single targeted valued integer. The task is to find a pair of two numbers from inside of our array that adds up to the target value, a number inside. What we will return will be the indexes of those two numbers that add up to the target value.

Our numbers Array: new int[]{1,2,3}

Our Target: 5

So since our target is 5. We will loop through our array and find those two numbers that add up to 5 which are 2 and 3.

for (int i = 0; i < numbers.length; i++) {
int num1 = numbers[i];
for (int j = i + 1; j < numbers.length; j++) {
int num2 = numbers[j];

Our solution will be a for loop followed by another for loop inside. This is called a nested for loop. The reason behind this is to start at index 0 of the array with index i = 0. The first for loop will fulfill its job. The nested for loop will start at index j = i + 1; because we can’t start from index 0 again to solve our solution. You will notice variables num1 and num2. This makes it easier for the programmer to solve the solution.

if (num1 + num2 == target) {
return new int [] {i,j};
}

Next, a condition must be made to sum the two numbers we found equal to the target. We will return the index values of the two numbers {i, j} as shown in the example above. The last thing is to make sure to return an array outside of our loops but inside of our method. We do this because of the array {} that holds i and j as a result of the if statement. See the below example.

public class Solution {
public static int[] twoSum(int[] numbers, int target) {
for (int i = 0; i < numbers.length; i++) {
int num1 = numbers[i];
for (int j = i + 1; j < numbers.length; j++) {
int num2 = numbers[j];
if (num1 + num2 == target) {
return new int [] {i,j};
}
}
}
return new int [] {};
}
}

And now we have done it! We have solved the Two Sum DSA problem! The inputs were:

Our Array: new int[]{1,2,3}

Our Target: 5

The output should be: new int[]{1,2}

Hopefully, this article helped you learn more about the Two Sum DSA problem! Till next time, please comment and follow! Thank you! :)

--

--

Norbert Seals
Strategio

Hello, my name is Norbert and I reside in Miami, FL. My favorite sport is basketball and I love to play video games! I am currently a Technologist at Strategio!