Microsoft Interview Question for Software Engineer / Developers






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

1. Store the index of the last element of the array (say in 'last').

2. Let x = rand()%M. x will be in [0,M-1] range. Output arr[x] and replace arr[x] with arr[last]. Do last--.

3. Repeat this step for N times, each time applying the mod operation with dividend one less than in the previous step i.e. rand()%(M-1), rand()%(M-2) and so on.

4. Time: O(N). Space: O(1).

5. In the above algorithm, you will be changing the array contents. If you want to maintain the array in the same state, you can keep track of all the changes you are making to the array and undo them after you printout the N values. This is better than making a copy of the array when M is large.

- spookymulder83 December 17, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

How do you maintain track of all the changes that have been made? wont' this consume memory?

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

M=arr.size();
while(N>0){
        indx = rand()%M;
        swap(arr[indx],arr[M-1]);
        --N;-M;
} //the last N elements are the selected distinct integers//Time: O(N), Space : O(1)

- blueskin December 17, 2010 | 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