...

/

Solution Review: Find Two Numbers that Add Up to the Given Value

Solution Review: Find Two Numbers that Add Up to the Given Value

This review provides a detailed analysis of the different ways to solve the "Find Two Numbers that Add Up to the Given Value" challenge.

Solution #1: Brute force

Press + to interact
namespace chapter_2
{
class Solution
{
//Find Two Numbers that Add up to "value" (Brute Force)
static int[] findSum(int []arr, int value, int size)
{
int[] result = new int[2];
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (arr[i] + arr[j] == value)
{
result[0] = arr[i];
result[1] = arr[j];
return result; // containing 2 numbers
}
}
}
return arr;
}
static void Main(string[] args)
{
int size = 5, value = 9;
int []arr = { 2, 4, 5, 7, 8 };
if (size > 0)
{
int[] arr2 = findSum(arr, value, size);
int num1 = arr2[0];
int num2 = arr2[1];
if ((num1 + num2) != value)
Console.WriteLine("Not Found");
else
{
Console.WriteLine("Number 1 = " + num1);
Console.WriteLine( "Number 2 = " + num2 );
Console.WriteLine("Sum = " + (num1 + num2).ToString() );
}
}
else
{
Console.WriteLine( "Input Array is Empty!");
}
}
}
}

This is the most time-intensive but intuitive solution. Traverse the whole array of the given size for each element in the array, and check if any of the two elements add up to the given number value. Use a nested for-loop, and iterate over the entire array for each element.

Time complexity

Since you iterated over the entire array (size nn ...