## Yahoo Interview Question

Software Engineer / DevelopersAnd what about the elements in between the first and last sqrt(n)?

Say n = 25. Your method only sorted 10 elements. lol.

@Anonymous2: What magical elements are there between the first n-sqrt(n) and last sqrt(n)? I am dying to know.

Just wondering what significance sqrt has in the problem. Sorting the rest and merging them would work with any partition of the array.

I think yahoo doesn't want to recruit any more. It seems that they just want to continue interview processes just like that. And they seem to ask really weird questions. Recently a friend of mine faced really weird questions in a yahoo interview.

take the last sqrt(n) elements and insert them into the n-sqrt(n) using binary search.

time complexity is O(sqrt(n)*logn)

You mean insert last n-sqrt(n) elements using binary search in first sqrt(n) elements..

Complexity would be O(sqrt(n) * n). no MAGIC exists to insert at an arbitrary location of array without linear complexity to shift.

The complexity is O(n) in the worst case. As given, the n - sqrt(n) elements are sorted. Let's assume (a) we are doing insertion sort and (b) the sqrt(n) elements are the smallest sqrt(n) elements in the entire array. In such a case, each insertion requires shifting of O(n-sqrt(n)) elements. Therefore, the total time to sort would be O (sqrt(n) * (n - sqrt(n) ) ) = O(n).

Using Insertion Sort: As maximum of the elements of the array (n - sqrt(n)) are already sorted and only sqrt(n) elements are not sorted, so for a large amount of input, insertion sort would be better. Complexity of the algorithm: O(n * sqrt(n)).

Using Binary Search and Insertion: Suppose an array of 25 elements looks like: 6,7,8,9,10, ....., 25, 5,4,3,2,1. It is the case for the worst case. Just consider the time needed to properly place the last element 1. When it's the turn to insert 1, all other elements are already sorted. So do a binary search on all the (n-1) elements in time log(n-1). Now 1 must be inserted at the front of the array. This insertin needs all the (n-1) elements to move in the right direction. Time complexity: O(n-1). So for a single element to insert properly, the time complexity is: O(n-1) + O(log(n-1)). So for sqrt(n) number of elements this is: O(sqrt(n) * (O(n-1) + O(log(n-1)))). or simply: O(sqrt(n) * n).

It depends on the case which method to use.

I think the intent here is that, we have 2 methods.

- bebo August 26, 2011- Sort the rightmost half and merge (in place). Complexity = n + sqrt(n)log(n)

- Use the insertion sort way . Complexity = n*sqrt(n)

So, 1st method is better than 2nd.