Introduction
Hi friends!! In this blog, we will learn about how to solve two sum problems is Java. The Two Sum problem involves finding two numbers within an array that add up to a specific target sum. Suppose we have given an array of integers and a target sum. The task is to determine the indices of the two numbers in the array that add up to the target.
For example, consider the array [2, 7, 11, 15]
and a target sum of 9
. The pair of numbers [2, 7]
from this array sums up to the target 9
, so the indices of these numbers would be 0
and 1
.
How Can We Implement The Two Sum Problem In Java?
public class TwoSumProblemProgram {
public static int[] twoSum(int[] nums, int target) {
// Loop through the array elements
for(int i = 0; i < nums.length - 1; i++) {
for(int j = i + 1; j < nums.length; j++) {
// Check if the sum of current pair equals the target
if(target == (nums[i] + nums[j])) {
// If found, return the indices of the two numbers
return new int[]{i, j};
}
}
}
// If no such pair is found, return an array with a default value (0)
return new int[]{0};
}
public static void main(String[] args) {
int[] nums = {2, 11, 7, 15};
int target = 9;
// Find the indices of two numbers that sum up to the target
int[] result = twoSum(nums, target);
// Print the numbers that add up to the target
System.out.println(nums[result[0]] + " + " + nums[result[1]] + " = " + target);
}
}
Output
Conclusion
In this blog, we have seen how we solve two sum problems in Java. Thanks for reading, and I hope you like it. If you have any suggestions or queries on this blog, please share your thoughts. You can read my other articles by clicking here.
Happy learning, friends!