X

DAYS

:

HOUR

:

MINS

:

SEC

Copied to Clipboard
Subarray Inversions
Medium Accuracy: 57.97% Submissions: 126 Points: 4

Given an array arr[] of N integers, the task is to find the sum of the number of inversions in all subarrays of length K. To clarify, determine the number of inversions in each of the n k + 1 subarrays of length k and add them together.

For example, if i and j are two different indices of an array arr[] such that i < j and arr[i] > arr[j], it is an inversion.

Example 1:

Input: N = 4, K = 3
arr[]= {1, 6, 7, 2}
Output: 2
Explanation: There are two subarrays
of size 3, {1, 6, 7} and {6, 7, 2}.
Count of inversions in first subarray
is 0 and count of inversions in second
subarray is 2. So sum is 0 + 2 = 2.

Example 2:

Input: N = 8, K = 4
arr[]= {12, 3, 14, 8, 15, 1, 4, 22}
Output: 14 

This is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function inversion_count() that takes array a[], integer N, and integer K as parameters and returns the desired result.

Expected Time Complexity: O(N2).
Expected Auxiliary Space: O(N).

Constraints:
1 ≤ N ≤ 103

We are replacing the old Disqus forum with the new Discussions section given below.