~/coding-interview/counting-inversions-problem.md

Counting Inversions Coding Problem

2 min readMay 19, 2019by Gorav Singal#coding-interview#counting-inversions
// TL;DR

Use modified merge sort — count cross-inversions during the merge step. Every time a right-side element is placed before remaining left-side elements, add the count. O(n log n).

Counting Inversions Coding Problem

** Inversion There is an array(a) and two indexes i and j. Inversion is the element for whom i < j and a[i] > a[j]

Example:

2 6 5 4 8

# Inversion pairs
(6, 5) (6, 4) (5, 4)

# Total inversion = 3

Counting Inversion Algorithm - Brute Force - O(n^2)

Lets look at simple brute force algorithm:

public void calculate_bad(int[] arr) {
    int count = 0;
    for (int i=0; i<arr.length-1; i++) {
        for (int j=i+1; j<arr.length; j++) {
            if (arr[i] > arr[j]) {
                count ++;
                System.out.println(arr[i] + " " + arr[j]);
            }
        }
    }
    System.out.println("Total inversions: " + count);
}

Above is a simple algorithm. Lets think about optimizing this.

Thoughts about Optimizing Algorithm

Next better number than O(n^2) is O(n log n) Can we do it in O(n log n)? Can we apply divide and conquer algorithm in this? If somehow, we can think what we will achieve by dividing the input array?

Hint Can we use Merge Sort? Yes

How In function where we merge two sorted sub-problems. Before sorting, their positions are actually relatively left and right which we want. The advantage of using merge sort is that, we know each of left and right array is sorted.

So, while comparing, one thing is for sure. For every element in left array, the index-i is always lesser than the index from right sorted sub-array. If we know, that one element in left sub-array which is greater than an element from right array.

Inversion Count algorithm

In above image, we know in left array that index=4 element is greater than element in right array at index=2 WHat it means, we found one inversion pair. In addition to that, we know every element in left array from index=4 onwards will be greater than element in right array where we found at index=2 Which means, in above example, we found total 3 inversion pairs for this condition.

And, we keep on continuing like this.

The code of algorithm taking O(n log n)

private void calculate_good_recursive(int[] arr, int l, int m, int r) {
    int l1 = m-l+1;
    int l2 = r-m;
    
    int[] left = new int[l1];
    for (int i=0; i<l1; i++) {
        left[i] = arr[l+i];
    }
    
    int[] right = new int[l2];
    for (int i=0; i<l2; i++) {
        right[i] = arr[m+i+1];
    }
    
    int lindex = 0;
    int rindex = 0;
    while (lindex < l1 && rindex < l2) {
        if (right[rindex] < left[lindex]) {
            for (int jj=lindex; jj<l1; jj++) {
                System.out.println(left[jj] + " " + right[rindex]);
            }
        }
        
        if (left[lindex] <= right[rindex]) {
            arr[l] = left[lindex];
            lindex ++;
        }
        else {
            arr[l] = right[rindex];
            rindex ++;
        }
        
        l++;
    }
    while (lindex < l1) {
        arr[l] = left[lindex];
        l++; lindex ++;
    }
    while (rindex < l2) {
        arr[l] = right[rindex];
        l++; rindex ++;
    }
}

public void inversions_merge_sort_method(int[] arr, int l, int r) {
    if (l < r) {
        int m = (l+r)/2;
        inversions_merge_sort_method(arr, l, m);
        inversions_merge_sort_method(arr, m+1, r);
        
        calculate_good_recursive(arr, l, m, r);
    }
}

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

System Design Interview Vocabulary Notes

System Design Interview Vocabulary Notes

In this post, we will see some of the frequently used concepts/vocabulary in…

Coding Interview - Facebook System Design Interview Types

Coding Interview - Facebook System Design Interview Types

System design interview is pretty common these days, specially if you are having…

Find the maximum sum of any continuous subarray of size K

Find the maximum sum of any continuous subarray of size K

Introduction You are given an array of integers with size N, and a number K…

What FAANG companies expect in their interview from candidates

What FAANG companies expect in their interview from candidates

Its every software engineer’s dream to work with the big FAANG companies…

Magical usage of Bitwise operators - Get optimized solutions for many arithmatic problems

Magical usage of Bitwise operators - Get optimized solutions for many arithmatic problems

Introduction I will list some of the interesting usage of bitwise operators…

How to prepare for your next Coding Interview

How to prepare for your next Coding Interview

Here are some tips while preparing for your coding interviews. 1. Do study or…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…