Interview Question


Country: India




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

1) use quicksorts partition method to split into half, this will separate your array into elements: < median and >= median
2) on the upper half of this array, use the same partition method to separate on kth position, you will then have an array of median ... median + k in O(n) time
3) this array you need to sort which will lead to the O(n + k * log(k))

things to consider:
- median is ambigious as there exists a median element if the array is of odd size, if of even size, there is an floor-median and a ceiling median and in statistics the real median is the average of them, here either the floor or ceiling is ment I suppose.
- the partition method has a few properties that are not so nice if implemented in a primitive way and applied for example on a sorted array or an array with all the same elements in it. Randomization is an approach, and split into three parts < = > is an alternative

- Chris December 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

@Ankita: some pivot will divide into half, most often not the first of course, see partitionAroundKth:

int partition(int *array, int first, int last)
{
// typical partition code
// returns arbitrary index in the range [first, last] which is the
// index of the pivot
}

void partitionAroundKth(int *array, int first, int last, int k)
{
int pi = -1;
while(pi != k)
{
pi = partition(array, first, last);
if(pi > k) last = pi - 1;
if(pi < k) first = pi + 1;
}
}

- Chris December 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

@ChrisK
Thanks for reply!
But what if the data has random numbers, and the pivot I select does not divide into half?Is there any specific way in selecting pivot?
Generally I prefer using last element as pivot

- Ankita December 29, 2016 | 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