Facebook Interview Question for Software Engineer / Developers


Country: United States
Interview Type: In-Person




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

Method 1: Sort the array and then do the following (O(n log n)):

p=0,q=n-1;
while(p<q)
{
  if(a[p]+a[q]==k)
  {
      cout<<a[p]<<"\t"<<a[q];
      p++;
      q--;
   }
   else if(a[p]+a[q]>k)
      q--;
   else 
      p++;
}

Method 2: We can use hash table (O(n)):

for(i=0;i<n;i++)
{
   Complement=K-a[i];
   HashTable[a[i]]=i;
   if(SearchHashTable(Complement)!=-1)
     cout<<"Indices:\t"<<HashTable[Complement]<<"\t"<<i<<endl;
}

- Anonymous September 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

The second method has a bug. It won't answer correctly given the array {1,5,8}, K = 10. It would say 5,5 but there is only one 5.

for(i=0;i<n;i++)
{
   Complement=K-a[i];
   if(SearchHashTable(Complement)!=-1)
     cout<<"Indices:\t"<<HashTable[Complement]<<"\t"<<i<<endl;
   HashTable[a[i]]=i;
}

- Miguel Oliveira September 25, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

the complexity of Method 2 is O(n)? did u assume that searchHashTable could be done in constant time?

- chuang24@buffalo.edu September 25, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

BTW, method 1 is pretty good!

- chuang24@buffalo.edu September 25, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 votes

fix the bug Anonoymous

- S O U N D W A V E September 28, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Won't the following be good?

for(i=0;i<n;i++)
{
   Complement=K-a[i];
   HashTable[a[i]]=i;
   Index = SearchHashTable(Complement);
   if(Index!=-1 && Index != i)
     cout<<"Indices:\t"<<HashTable[Complement]<<"\t"<<i<<endl;
}

- atuljangra66 October 16, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@atuljangra66 your code will fail for this {1, 5, 5, 8}

Initialize whole hash table with all -1s.
for(i=0;i<n;i++)
{
  hashTable[a[i]]++;
}

for(i=0;i<n;i++)
{
   Complement=K-a[i];
   Index = SearchHashTable(Complement);
   if(Index!=-1)
     cout<<"Indices:\t"<<HashTable[Complement]<<"\t"<<i<<endl;
}

- Psycho October 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

for O(nlogn) also you can take a number x and binary search for K-x same complexity.

- kkr.ashish February 10, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

O(N):

boolean exists(int[] arr, int k) {
// Transfer into HashSet and taking into account duplicates
	Set<Integer> set = new HashSet<Integer>();
	for (int c : arr) {
		if (set.contains(c))
			if (c*2 == k) return true;
		set.add(c);
	}
// Now that all duplicates have been accounted for, do a simple search and match
	for (int c : set) {
		if (set.contains(k-c)) return true;
	}
	return false;
}

- leonard.loo.ks November 13, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Can you elaborate more on "randomly sorted"? Perhaps also give an example.

- Sidhu September 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I think he means a sorted list of random numbers. That's the only way the problem makes sense to me.

- styles May 02, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

1. NlogN to sort (from smallest to largest), then two indices: i=0, j=N; if A(i)+A(j) > k, j--; if(A(i)+A(j) < k) i++
2. bucket sort?

- Anonymous September 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

from collections import defaultdict

def check(a):
    #a = [...] # array
    n = len(a) 
    h = defaultdict(int)
    for i in range(n):
        h[a[i]] += 1
    for i in range(n):
        d = k - h[a[i]]
        if (h[d] > 0) return True
    return False

- linkinpak September 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

If we know about the range (max value of elements) than we use redix sort and than use first approach of Anonymous .

- Ajeet September 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

O(N) -- two pointer one at starting and one at end
i=0;
j=a.length
if a[i]+a[j]==NUM
return a[i] and a[j]
if a[i]+a[j]>NUM
j--
else
i++

O(NLOGN)
for each a[i]
do binary search in the sorted array to find the othe number which makes up the sum

- Sudipta October 02, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int diff = k - a[i] // where i is an index of the array
Then find element equals to 'diff' in array except index i
This gives a O(n) solution, right?

- Danny Sun October 09, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

-(BOOL)checkSumInArray:(NSArray *)myArray isEqualTo:(NSInteger)k{
    int front = 0;
    int back = [myArray count]-1;
    BOOL result = NO;
    //sort array
    [myArray sortedArrayUsingSelector: @selector(compare:)];
    while (front < back) {
        NSInteger sum = [myArray[front] integerValue] + [myArray[back] integerValue];
        if (sum == k) {
            result = YES;
            break;
        }
        else if (sum > k){
            back--;
            continue;
        }
        else{
            front++;
            continue;
        }
    }
    return result;
    
}

- kchronis October 22, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

O(N logN):

static bool IsExistsPairThatThierSumIsK(int[] a, int k)
{
    for (int i = 0; i < a.Length; i++)
    {
        int j = FindLeftmost(a, k - a[i]);
        
        if (j == -1) continue;
        
        if (i != j || (i + 1 < a.Length && a[i] == a[i + 1])) return true;
    }
    
    return false;
}

static int FindLeftmost(int[] a, int k)
{
    int l = 0;
    int r = a.Length - 1;
    
    while (l < r)
    {
        int m = l + (r - l) / 2;
        
        if (a[m] >= k) r = m;
        else l = m + 1;
    }
    
    return a[l] == k ? l : -1;
}

O(N):

static bool IsExistsPairThatThierSumIsK2(int[] a, int k)
{
    int l = 0;
    int r = a.Length - 1;
    
    while (l < r)
    {
        if (a[l] + a[r] == k) return true;
        else if (a[l] + a[r] > k) r--;
        else l++;
    }
    
    return false;
}

- ZuZu October 28, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.HashSet;
import java.util.Set;
public class TwoNumSum {
	public static void main(String[] args) { 
		int sum = 20;
		int [] nums = {1,4,5, 16, 17, 20};
		for(int i : twoNumSum(sum, nums))
			System.out.print(i + "\t");
	}
	public static int[] twoNumSum(int sum, int [] nums){
		//This is O(n) algorithm. 
		int [] r  = new int[2];
		Set <Integer> hs = new HashSet<Integer>();
		for(Integer intg: nums )
			hs.add(intg); 
		
		for(Integer intg: nums ){
			if (hs.contains(sum - intg)){
				r[0] = intg;
				r[1] = sum -intg;
			}
		}
		return r;
	}
}

- O(n) December 10, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int sum_pair_n(const int *i, const int size, const int sum)
{
	int tail = size - 1;
	int head = 0;
	int iSum;

	while(head < tail)
	{
		iSum = i[head] + i[tail];
		if(iSum == sum)
		{
			return 1;
		}
		else if(iSum < sum)
		{
			head++;
		}
		else if(iSum > sum)
		{
			tail--;
		}
	}
	return 0;
}

int sum_pair_logn(const int *i, const int size, const int sum)
{
	int head = 0;
	int look_for;

	while(head < size)
	{
		look_for = sum - i[head];
		int h=head+1, t=size;
		while(h<=t)
		{
			if(i[(h+t)/2] == look_for)
			{
				return 1;
			}
			else if(i[(h+t)/2] > look_for) t = (h+t)/2 - 1;
			else if(i[(h+t)/2] < look_for) h = (h+t)/2 + 1;
		}
		head++;
	}
	return 0;
}

int main()
{
	int i[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
	printf("%d\n", sum_pair_n(i, 10, 5));
	printf("%d\n", sum_pair_logn(i, 10, 4));
	return 0;
}

- sagar019 January 27, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

1. Sorting the array in (NlogN) and then find out the pair in (logN) by using binary search.
2. Divide n Conquer would go.

- Anonymous September 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

1. Pair can be found in (lg n) time??
For your solution, it'll be (n lg n) time as u'll hv to consider each element and find its pair using Binary search.

- Roshan September 26, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Ya, its a Typo. It will take (log n + log n-1 + log n-2......) to find a pair.
Thanks for correcting me.

- Anonymous September 26, 2013 | Flag


Add a Comment
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.

Learn More

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.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More