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=5

A=4

A=-3

A=1

A=2

A=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;
}
}

Watch our latest video on C# interview questions & answers :- Visit us @ www.questpond.com or call us at 022-66752917... read more #### .NET interview questions 6th edition (Sixth edition) - By Shivprasad Koirala #### Exception Handling in C# using example step by step #### C# Design pattern interview questions with answers: - How Singleton is different from Static class? #### MVC vs ASP.NET ( MVC Interview question with answers )? #### What is the difference between each version of MVC 2, 3, 4, 5 and 6? (MVC Interview Questions) 