Solution
Let’s try the most frequently used type of the divide-and-conquer strategy. Split the input sequence into two halves, and , and make a recursive call for each of them. This allows us to compute all inversions that lie in the same half. But it does not reveal the numbers of split inversions, i.e., the number of pairs such that lies in the left half, lies in the right half, and .
Stop and think: Consider an element in . What is the number of split inversions that belongs to?
Given an array and an integer , let be the number of elements in that are smaller than . Since the answer to the question above is , our goal is to rapidly compute .
It is equal to the number of elements in that are smaller than . This way, we face the following problem: given a sequence of integers and an integer , find the number of elements in that are smaller than . We can do it in time in the case of the unordered array (since each element of the array has to be checked) and in time in the case of an ordered array by using the binary search.
Exercise break: Show how to implement a method for counting the number of elements of that are smaller than in time .
This way, we arrive at the following divide-and-conquer algorithm:
:
:
return
of
of
sort
for in :
+ $
return
The running time (where is the length of ) satisfies a recurrence relation
The term includes two things: sorting and answering queries. This recurrence cannot be plugged into the master theorem directly as the term is not of the form for a constant . Still, we can analyze this recurrence in the same fashion. The recursion tree has levels, the total size of all problems on every level is equal to , and the total time spent on every level is . Therefore, the total running time is . Instead of formally proving it, we will improve the above algorithm so that it works in time .
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.