X Interview Question

Write a method that counts how many elements in an unsorted array are out of order.

Interview Answers

Anonymous

Jan 14, 2013

use the divide and conquer O(nlogn) algorithm similar to merge sort. while merging count the number of elements out of order. example: merging 4, 5 and 2, 3 should give 4.

2

Anonymous

Apr 2, 2013

As Anonymous said use merge sort and increment a count whenever you merge from the right array into the main array when there are still elements remaining in the left array. This indicates an element is out of order. An extension of this problem is counting the number of inversions in an array. http://stackoverflow.com/questions/337664/counting-inversions-in-an-array

1

Anonymous

Apr 27, 2012

I'm curious about how do you define "out of order"? For example, for array [10,1,2,3,4,5,6,7,8,9], by what's algorithm the number will be 10, but by e's algorithm the number will be just 1

1

Anonymous

Aug 19, 2012

I think this question is just a variation of finding largest increasing sub-sequence. Find its size (say k) Ans is n-k

1

Anonymous

Apr 6, 2012

You mean how many elements are not in the place they should be after they are sorted or what? If so just make a duplicate array and sort it, then go through both arrays and compare whether the element at array_sorted[i] and array_unsorted[i] are different.

Anonymous

Apr 26, 2012

You don't need to duplicate the array. Starting with the first element, compare to the next element in the array. If it's less than the current value, add one to the count and then look at the next value.