Coding problem
Count the out-of-order pairs
The task
A search team compares today's ranking with the ideal order and reports how far off it is: the number of pairs that are in the wrong order.
Complete CountInversions(int[] values). Count the pairs of positions i < j with values[i] > values[j]. Equal values are not out of order. Do not change the caller's array. Return a long: the count can be larger than an int holds.
Signature
public static long CountInversions(int[] values)
Examples
[3, 2, 1]→3. Every one of the three pairs is in the wrong order.[2, 1, 2, 1]→3. Each 2 before a later 1 counts; equal values do not.
Limits: Up to 400,000 values.
The tests check: an empty array, one value, sorted values, equal values, a mixed array, negative values, int.MaxValue before int.MinValue, that your method leaves the array unchanged, and 400,000 falling values (a count beyond int, in time).
Hints
Your code
Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;
public static class Solution
{
// Counts the pairs i < j with values[i] > values[j], without changing values.
public static long CountInversions(int[] values)
{
throw new NotImplementedException();
}
}This problem comes with TechInterviewNotes Full Access
Unlock all paid content on TechInterviewNotes.