...

/

Solution: Find Two Numbers that Add up to "n"

Solution: Find Two Numbers that Add up to "n"

This review provides a detailed analysis of the different ways to solve the previous challenge.

Solution #1: Brute force

Press + to interact
class CheckSum {
public static int[] findSum(int[] arr, int n) {
int[] result = new int[2];
//traversing the array
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
//checking if sum of two values equals n
if (arr[i] + arr[j] == n) {
result[0] = arr[i];
result[1] = arr[j];
return result; // containing the two numbers
}
}
}
return arr;
}
public static void main(String args[]) {
int n = 9;
int[] arr1 = {2, 4, 5, 7, 8};
int[] arr2 = findSum(arr1, n);
int num1 = arr2[0];
int num2 = arr2[1];
if ((num1 + num2) != n)
System.out.println("Results not found!");
else
System.out.println("Sum of " + n + " found: " + num1 + " and " + num2);
}
}

This is the most time intensive but intuitive solution. It is a lot like a modified version of a linear search. The whole array is traversed for each element and checked for any two elements that add up to the given number value. If they are found, we print them out. To do all of the above, we use a nested for loop and iterate over the entire array for each element

Time complexity

Since we iterate over the entire array (size nn) nn times, the time complexity is O(n2)O(n^2) ...

Access this course and 1400+ top-rated courses and projects.