This problem is about finding two elements from array/list which equal to the given sum value.
Ex:
CASE# 1: source = [1, 2, 3, 9], sum = 8, in this scenario we need to find two elements from the given list/array whose sum is 8, based on permutations you find none of the element's total is 8 so this problem will fail to find the value of sum.
CASE# 2: source = [1, 2, 4, 4], sum = 8, in this scenario we need to find two elements from the given list/array whose sum is 8, based on permutations you find at least a pair whose sum is 8 so this problem will success to find the value of sum.
Here I am going to an efficient solution, which means it'll provide you a solution in minimal iteration/efforts.
Ex:
CASE# 1: source = [1, 2, 3, 9], sum = 8, in this scenario we need to find two elements from the given list/array whose sum is 8, based on permutations you find none of the element's total is 8 so this problem will fail to find the value of sum.
CASE# 2: source = [1, 2, 4, 4], sum = 8, in this scenario we need to find two elements from the given list/array whose sum is 8, based on permutations you find at least a pair whose sum is 8 so this problem will success to find the value of sum.
Here I am going to an efficient solution, which means it'll provide you a solution in minimal iteration/efforts.
- This is list base operation
private static bool PairForSumExists(List<int> sourceList, int sum)
{
List<int> resultList = new List<int>();
foreach (int item in sourceList)
{
if (resultList.Contains(sum - item))
return true;
resultList.Add(sum - item);
}
return false;
}
- This is an array base operation
private static bool PairForSumExists(int[] sourceArray, int sum)
{
int[] resultArr = new int[(sourceArray.Length)];
for (int counter = 0; counter < sourceArray.Length; counter++)
{
int item = sourceArray[counter];
if (resultArr.Contains(sum - item))
return true;
resultArr[counter] = (sum - item);
}
return false;
}
In this way, you can find the solution for the given problem, if you have batter solution then it's my pleasure if you share with me your knowledge.
Of course, I can provide here the explanation for this code written here, I suggest here to debug this code on your own by creating a console application that will provide you batter understanding of this.
Still, if you have any query/confusion to digest it plz. put your questions/suggestions in the comment box
If you want this code sample then mention in comment section with your email, I'll share on same
Put in the comment section which algorithm you want to appear in my next blog.
Happy coding.