Country: India
Interview Type: Written Test

Comment hidden because of low score. Click to expand.
1
of 1 vote

This is actually not O(n). It depends on the implementation of set.contains(). If it is linear search, then it will be O(n^2). If it is binary search, it will be O(n lg n)

Comment hidden because of low score. Click to expand.
0

No set.contains()in java is of constant time complexity. It uses hash for searching. So the algorithm is actually O(n).

Comment hidden because of low score. Click to expand.
0

What if we are not supposed to use built-in classes like HashSet and all. What if we need to implement this in C? Then I suppose, O(n) will not be possible.

Comment hidden because of low score. Click to expand.
1
of 1 vote

``````If we can not use any extra space, then the problem can be solvable in O(n lg n) time.
1. Let the given array be A. Sort the array in O(n lg n)
2. For each element A[i] find SUM-A[i] in A in O(lg n) time using binary search.
3. If binary search in step-2 returns TRUE then return TRUE.
4. Else return FALSE``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

The complexity of this program is O(n). I am not sure if the problem can be done at a lesser complexity

``````int find(int sum, int array[])
{
HashSet<Integer> set = new HashSet<Integer>();
for(int i =0 ;i < array.length;i++)
{
}
for(int i =0; i< array.length-1;i++)
{
if(set.contains(sum-array[i]))
return 1;
}
return 0;
}``````

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.