Facebook Interview Question for Software Engineer / Developers






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

void shuffle(Element* array, int size){
    for (int i=0; i<size; i++) {
      ind = rand(i,size);
      swap(array[i], array[ind]);
    }
}

- Anonymous April 18, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This doesn't shuffle with 1/n probability

- KarateKamli April 21, 2009 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

No, it does.

Proof: First element is chosen from the whole array uniformly at random, so the probability that itself will be chosen is 1/n. The probability that second element will be itself is the probability that the first element in the shuffled version is not the second element in the first array (and this probability is (n-1)/n) times the probability that the second element in the shuffled array will be the second element in the original array (which requires choosing itself, and that probability is 1/(n-1)). So the product makes 1/n. In general, the probability that kth element will remain in place is the probability that some (k-1) permutation of the array which does not include kth element will be chosen for the first (k-1) places in the shuffled array (which is P(n-1,k-1)/(n*...*(n-k+2))) times kth element will be chosen among the remaining elements (which is 1/(n-k+1)). This product is always 1/n.

- onur.cobanoglu.84 July 11, 2010 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

// k is a random number between 0, i. Prob = 1/(i+1)
// Total Prob = 1/(1 * 2 * ... * N) = 1/(N!)
// this makes the shuffle to be uniformly randomly selected from the possible N! permutations of the array.
void knuth_shuffle( int * array, int size )
{
for ( int i = size - 1; i >= 0; i++ )
{
int k = (int)(rand() * i);
swap( &array[i], &array[k] );
}
}

- Anonymous October 02, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

correct! using Knuth shuffle!

- beyondfalcon February 24, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

should be i-- in the loop

- anonymous October 08, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

void shuffle(Element* array, int size){
    for (int i=0; i<size; i++) {
        int toSwap = Rand()%size;
        if(toSwap!=i) {
            Element temp = array[toSwap];
            array[toSwap] = array[i];
            array[i] = temp;
        }
    }
}

- Anonymous April 15, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I think this one is correct, and can be proved.

any other ideas???

- Anonymous April 17, 2009 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Lookup the wiki on shuffling. Apparently the above is one of the most common ways of getting it _wrong_.

- T April 17, 2009 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

when we are shuffling it means permutations any permutation will work ,proof let ther be n elements hance number of permutations can be n!,now let us fix one element to its position then number of permutatons become (n-1)!.now probability beomes(n-1)!/n! which is 1/n. hence select any permutation randomly will give you the desired result.

- Anonymous August 31, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Why don't people try proving their algorithms?

btw, lookup fischer yates shuffle.

- Knuth April 16, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is right. Although Yates shuffle is O(n^2), there is a better version that does it in O(n). Check it out in wikipedia.

- memo June 10, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

How about rotating left by one position with a probability of 1/n?

- danana April 16, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

then its not shuffling any way

- KarateKamli April 21, 2009 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

How about making the new index as:
1) Generate a random no. 'r' initially once
2) Make new_index = (old_index + r)%n

- Saurabh April 23, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think it does. Iterate through all the cards, for every card, swap it with a random card that has not been visited yet. So, random will run from i + 1 to card count - 1 where i is the current position.

- Metta April 26, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Generate a random number k between 1 and n and rotate the array to the left (or right) k times.
This way each element has a 1/n probability of remaining there

- Manish Krishnan April 30, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Manish - your solution just wont work. When, k=1,2,3, none of the elements will be in its original position. When k=4, all elements will be in their original position, which is the only case when it works. So, the probability isn't 1/n.

- CodeJunkie May 14, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

there are n! of permutations. Let us numbering them from 1 to n! and select 1 random number between 1 and n! (inclusive), and call this k, so kth permutation of this current array will be the result after shuffle.

- emotionalBlind June 20, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

@emotionalBlind
I guess you are referring to the Knuth shuffle, which I believe is correct.

- name August 26, 2009 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int* shuffle_array(const int* nArray, const int nSize)
{
int* p = new int(nSize);
//float a = rand();
for (int i = 0; i < nSize; i ++) {
float a = rand();
int n = a*(i+1);
swap(p[i], p[n]);
}
return p;
}

- Anonymous January 16, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

this can be proved to have the equal opportunity for all the numbers

- Anonymous January 16, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

hehe, did not try the above code:

void shuffle_array(int* nArray, const int nSize)
{
//int* p = new int(nSize);
for (int i = 1; i < nSize; i ++) {
int ran = rand();
int n = ran %(i + 1);
if (n != i) {
swap(nArray[i], nArray[n]);
}
}
}

- Anonymous January 16, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Dudes...
The knuth shuffle is not order n. It's n^2.

- anon May 20, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

LoL@Anon ..... I'll advice u to read complexity analysis be4 trying such questions ....
Ignorance is a Bliss

- Fcker_24X7 November 23, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

how about :
1. loop through each number in the given array
2. for each element at index i, generate a random number between 1 and n. if the number is same as i (the probability of this happening is 1/n), the number needs to swapped out. hence save this index using a temp variable (say last_element_to_be_swapped).
3. now continue with the next element and perform step 2. if it needs to swapped out, swap it with last_element_to_be_swapped. save the current index to last_element_to_be_swapped so that we can swap for further iterations.

As long as we find two elements that needs to be swapped, we are good. The only exception is when we only find one element that needs to be swapped, then we will not be able to shuffle with any other element. I am thinking of rerunning the loop again to handle this case. there are really low chances we run into same case again.

btb, this approach take O(n) obviously.

- baba_black_sheep November 28, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is my answer, how about it?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

void shuffle(int a[], const int n);

int main()
{
	int a[5]={1,2,3,4,5};
	const int n = 5;
	shuffle(a,n);
        return 0;
}

void shuffle(int a[], const int n)
{
	time_t t;
	srand((unsigned) time (&t)); //srand guarantees that each rand() function will
                                     //generate a really random number
	int *b=new int[n];
	int i,j;
	for(i=0;i<n;i++)
		b[i]=0;
	for(i=0;i<n;i++)
	{
		j=rand()%n;
		while(b[j] != 0)    //if there b[j] has already saved a value
			j = (j+1)%n;
		b[j]=a[i];
	}
	for(i=0;i<n;i++)
		a[i]=b[i];
	delete []b;
}

- jhzhu November 18, 2011 | Flag Reply


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