1. Back To Blog

C# Interview question :-Find Pair Of Integers in Array whose Sum is Given Number.

Recently, I have been to an interview and was asked to solve a problem with solution not having complexity of O(N square).

The problem was as follows :- 

A[0]=5

 

A[1]=4

 

A[2]=-3

 

A[3]=1

 

A[4]=2

 

A[5]=9

Now we need to find the complementary set of elements having sum of 6.

That is combination of 2 elements should give a sum of 6, so we had to write an algorithm to get the total number of such pairs in above example the total number of pairs will be 3.

I could achieve this using 2 for loops but the interviewer wanted a better way.

Below is the code with the comments

int[] arr = newint[]  5, 4, -3, 1, 2, 9 };
// Step 1 :- Sort the array in ascending manner
Array.Sort(arr);
int k = 6;
int left = 0;
int right = arr.Length - 1;
// Step 2 :- Take two pointers one which moves from
// the left of the array and the second from right of the array
while (left < right)
            
int sum = arr[left] + arr[right];
// Step 3 :- If sum is proper then add from the left
// substract from the right
if (sum == k)
                
Console.WriteLine(arr[left] + "  " +  arr[right]);
left = left + 1;
right = right - 1;
                }
elseif (sum < k)
                
// Step 4 :- If target total is greater than
// the sum then advance from the left
left = left + 1;
                }
elseif (sum > k)
                
// Step 5 :- If target total is less than
// the sum then substract from the right
right = right - 1;
                }
            }
Console.Read();

Watch our latest video on C# interview questions & answers :-

Shiv Prasad Koirala

Visit us @ www.questpond.com or call us at 022-66752917... read more

We are on Social