Geeksforgeeks

X

DAYS

:

HOUR

:

MINS

:

SEC

Error

Copied to Clipboard

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

**Your Task:**

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(N^{2}).

**Expected Auxiliary Space:** O(N).

**Constraints:**

1 ≤ N ≤ 10^{3}

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

Click here to view old Disqus comments.

Click here to view old Disqus comments.

Login to report an issue on this page.

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

YesLoading...

Subarray Inversions

...

Here is some troubleshooting advice:

- Reset the IDE using the second button on the top right corner.
- Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
- Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
- You can access the hints to get an idea about what is expected of you as well as the final solution code.
- You can view the solutions submitted by other users from the submission tab.

Here is some troubleshooting advice for contest problems

- Make sure you are not using ad-blockers.
- Disable browser extensions.
- We recommend using latest version of your browser for best experience.
- Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values.
- Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.