{"id":532,"date":"2025-07-07T19:14:42","date_gmt":"2025-07-07T13:44:42","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=532"},"modified":"2025-07-07T19:14:44","modified_gmt":"2025-07-07T13:44:44","slug":"count-inversions","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/count-inversions\/","title":{"rendered":"Count Inversions \u2013 GeeksforGeeks Solution Explained"},"content":{"rendered":"\n<p>If you\u2019re preparing for coding interviews, the &#8220;Count Inversions&#8221; problem is a classic and important question. In this blog, we\u2019ll explain the problem, walk you through the brute force and optimal solutions, and make everything easy to understand with code comments, dry runs, and clear explanations.<\/p>\n\n\n\n<p>Given an array of integers&nbsp;<strong>arr[]<\/strong>. Find the&nbsp;<strong>Inversion Count<\/strong>&nbsp;in the array.<br>Two elements arr[i] and arr[j] form an inversion if&nbsp;<strong>arr[i] &gt; arr[j]<\/strong>&nbsp;and&nbsp;<strong>i &lt; j<\/strong>.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/www.geeksforgeeks.org\/problems\/inversion-of-array-1587115620\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><em><strong>Inversion Count<\/strong>:&nbsp;<\/em>For an array, inversion count indicates how far (or close) the array is from being sorted. If the array is already sorted then the inversion count is 0.<br>If an array is sorted in the reverse order then the inversion count is the maximum.&nbsp;<\/p>\n<\/blockquote>\n\n\n\n<p><strong>Examples:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input<\/strong>: arr[] = [2, 4, 1, 3, 5]<br><strong>Output<\/strong>: 3\n<strong>Explanation<\/strong>: The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3).<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input<\/strong>: arr[] = [2, 3, 4, 5, 6]<br><strong>Output<\/strong>: 0\n<strong>Explanation<\/strong>: As the sequence is already sorted so there is no inversion count.<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input<\/strong>: arr[] = [10, 10, 10]<br><strong>Output<\/strong>: 0\n<strong>Explanation<\/strong>: As all the elements of array are same, so there is no inversion count.<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><br>1 \u2264 arr.size()&nbsp;\u2264 10<sup>5<br><\/sup>1 \u2264&nbsp;arr[i]&nbsp;\u2264 10<sup>4<\/sup><\/p>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-7c0cd5d7-53e1-491d-83e0-2fbc366bed75\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/count-inversions\/#0-brute-force-solution-nested-loops\" style=\"\">Brute Force Solution (Nested Loops)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/count-inversions\/#1-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/count-inversions\/#2-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/count-inversions\/#3-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/count-inversions\/#4-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/count-inversions\/#5-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/count-inversions\/#6-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/count-inversions\/#7-optimal-solution-merge-sort-approach\" style=\"\">Optimal Solution (Merge Sort Approach)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/count-inversions\/#8-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/count-inversions\/#9-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/count-inversions\/#10-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/count-inversions\/#11-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/count-inversions\/#12-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/count-inversions\/#13-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/count-inversions\/#14-final-thoughts\" style=\"\">Final Thoughts<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-brute-force-solution-nested-loops\">Brute Force Solution (Nested Loops)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>Let\u2019s solve the problem in the simplest way:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Check Every Pair:<\/strong><br>For each element, compare it with every element that comes after it.<\/li>\n\n\n\n<li><strong>Count Inversions:<\/strong><br>If the current element is greater than the next one, it\u2019s an inversion.<\/li>\n\n\n\n<li><strong>Why does this work?<\/strong><br>We check all possible pairs, so we count every inversion.<\/li>\n<\/ol>\n\n\n\n<p>This approach is easy to understand but not efficient for large arrays.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def inversionCount(self, arr):\n        n = len(arr)\n        count = 0\n        for i in range(0, n):\n            for j in range(i + 1, n):\n                if arr[i] &gt; arr[j]:      # found an inversion\n                    count += 1\n        return count\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">inversionCount<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">arr<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(arr)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        count = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> j <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(i + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> arr[i] &gt; arr[j]:      <\/span><span style=\"color: #6A9955\"># found an inversion<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    count += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> count<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#1E1E1E;color:#c7c7c7;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>We use two nested loops.<\/li>\n\n\n\n<li>For each pair (i, j) where i &lt; j, we check if arr[i] > arr[j].<\/li>\n\n\n\n<li>If true, we increment the inversion count.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-dry-run\">Dry Run<\/h3>\n\n\n\n<p><strong>Input:<\/strong><br><code>arr = [1]<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>(2,4): no inversion<\/li>\n\n\n\n<li>(2,1): inversion (count = 1)<\/li>\n\n\n\n<li>(2,3): no inversion<\/li>\n\n\n\n<li>(2,5): no inversion<\/li>\n\n\n\n<li>(4,1): inversion (count = 2)<\/li>\n\n\n\n<li>(4,3): inversion (count = 3)<\/li>\n\n\n\n<li>(4,5): no inversion<\/li>\n\n\n\n<li>(1,3): no inversion<\/li>\n\n\n\n<li>(1,5): no inversion<\/li>\n\n\n\n<li>(3,5): no inversion<\/li>\n<\/ul>\n\n\n\n<p><strong>Final count:<\/strong><br><code>3<\/code><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>\u00a0O(n^2)<br>Two nested loops for all pairs.<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>\u00a0O(1)<br>Only a counter variable is used.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-conclusion\">Conclusion<\/h3>\n\n\n\n<p>The brute force approach is simple and good for understanding, but it\u2019s too slow for large arrays.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7-optimal-solution-merge-sort-approach\">Optimal Solution (Merge Sort Approach)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"8-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>We can count inversions much faster using a modified merge sort:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Divide and Conquer:<\/strong><br>Use merge sort to divide the array into smaller parts.<\/li>\n\n\n\n<li><strong>Count Inversions During Merge:<\/strong><br>While merging two sorted halves, if an element from the right half is less than an element from the left, it means all remaining elements in the left half will form inversions with this right element.<\/li>\n\n\n\n<li><strong>Why does this work?<\/strong><br>Merge sort naturally compares and sorts elements, so it\u2019s efficient to count inversions during the merge step.<\/li>\n<\/ol>\n\n\n\n<p>This approach is efficient and works well for large arrays.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"from typing import List, Tuple\n\nclass Solution:\n    def mergeList(self, arr1: List[int], arr2: List[int]) -&gt; Tuple[List[int], int]:\n        n = len(arr1)\n        m = len(arr2)\n        i, j = 0, 0\n        count = 0\n        result = []\n\n        while i &lt; n and j &lt; m:\n            if arr1[i] &lt;= arr2[j]:\n                result.append(arr1[i])           # no inversion, add element\n                i += 1\n            else:\n                count += n - i                   # count inversions\n                result.append(arr2[j])           # add element from right half\n                j += 1\n\n        while i &lt; n:\n            result.append(arr1[i])               # add remaining left half elements\n            i += 1\n        while j &lt; m:\n            result.append(arr2[j])               # add remaining right half elements\n            j += 1\n\n        return result, count\n\n    def mergeSort(self, lst: List[int]) -&gt; Tuple[List[int], int]:\n        if len(lst) &lt;= 1:\n            return lst, 0                        # base case, no inversions\n\n        mid = len(lst) \/\/ 2\n        first_half = lst[:mid]\n        second_half = lst[mid:]\n\n        fh, cnt1 = self.mergeSort(first_half)    # sort and count left side\n        sh, cnt2 = self.mergeSort(second_half)   # sort and count right side\n\n        merged, count = self.mergeList(fh, sh)   # merge and count split inversions\n        return merged, cnt1 + cnt2 + count\n\n    def inversionCount(self, arr: List[int]) -&gt; int:\n        _, count = self.mergeSort(arr)\n        return count\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> typing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> List, Tuple<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">mergeList<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">arr1<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">], <\/span><span style=\"color: #9CDCFE\">arr2<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; Tuple[List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">], <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(arr1)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        m = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(arr2)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        i, j = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        count = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        result = []<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> i &lt; n <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> j &lt; m:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> arr1[i] &lt;= arr2[j]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                result.append(arr1[i])           <\/span><span style=\"color: #6A9955\"># no inversion, add element<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                i += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                count += n - i                   <\/span><span style=\"color: #6A9955\"># count inversions<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                result.append(arr2[j])           <\/span><span style=\"color: #6A9955\"># add element from right half<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                j += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> i &lt; n:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            result.append(arr1[i])               <\/span><span style=\"color: #6A9955\"># add remaining left half elements<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            i += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> j &lt; m:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            result.append(arr2[j])               <\/span><span style=\"color: #6A9955\"># add remaining right half elements<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            j += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> result, count<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">mergeSort<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">lst<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; Tuple[List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">], <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(lst) &lt;= <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> lst, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">                        <\/span><span style=\"color: #6A9955\"># base case, no inversions<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        mid = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(lst) \/\/ <\/span><span style=\"color: #B5CEA8\">2<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        first_half = lst[:mid]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        second_half = lst[mid:]<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        fh, cnt1 = <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.mergeSort(first_half)    <\/span><span style=\"color: #6A9955\"># sort and count left side<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        sh, cnt2 = <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.mergeSort(second_half)   <\/span><span style=\"color: #6A9955\"># sort and count right side<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        merged, count = <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.mergeList(fh, sh)   <\/span><span style=\"color: #6A9955\"># merge and count split inversions<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> merged, cnt1 + cnt2 + count<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">inversionCount<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">arr<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        _, count = <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.mergeSort(arr)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> count<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#1E1E1E;color:#c7c7c7;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>We use a modified merge sort.<\/li>\n\n\n\n<li>During the merge step, if an element in the left half is greater than one in the right, all remaining elements in the left half will form inversions with this right element.<\/li>\n\n\n\n<li>We count these inversions and add them to the total.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-dry-run\">Dry Run<\/h3>\n\n\n\n<p><strong>Input:<\/strong><br><code>arr = [1]<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Split into\u00a0<a href=\"https:\/\/www.geeksforgeeks.org\/problems\/inversion-of-array-1587115620\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>\u00a0and<\/li>\n\n\n\n<li><a href=\"https:\/\/www.geeksforgeeks.org\/problems\/inversion-of-array-1587115620\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>\u00a0splits into and\u00a0<a href=\"https:\/\/www.geeksforgeeks.org\/problems\/inversion-of-array-1587115620\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.geeksforgeeks.org\/problems\/inversion-of-array-1587115620\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>\u00a0splits into and\u00a0<a href=\"https:\/\/www.geeksforgeeks.org\/problems\/inversion-of-array-1587115620\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><\/li>\n\n\n\n<li>Merge and\u00a0<a href=\"https:\/\/www.geeksforgeeks.org\/problems\/inversion-of-array-1587115620\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>: inversion (4,1) \u2192 count = 1<\/li>\n\n\n\n<li>Merge and\u00a0<a href=\"https:\/\/www.geeksforgeeks.org\/problems\/inversion-of-array-1587115620\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>: inversion (2,1) \u2192 count = 2<\/li>\n\n\n\n<li>Merge and : no inversion<\/li>\n\n\n\n<li>Merge\u00a0<a href=\"https:\/\/www.geeksforgeeks.org\/problems\/inversion-of-array-1587115620\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>\u00a0and : inversion (4,3) \u2192 count = 3<\/li>\n<\/ul>\n\n\n\n<p><strong>Final count:<\/strong><br><code>3<\/code><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"12-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>\u00a0O(n log n)<br>Merge sort divides and merges arrays efficiently.<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>\u00a0O(n)<br>Extra space is used for temporary arrays during merge.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-conclusion\">Conclusion<\/h3>\n\n\n\n<p>The optimal solution is efficient and works well for large arrays. It\u2019s the best approach for interviews and practical use.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"14-final-thoughts\">Final Thoughts<\/h2>\n\n\n\n<p>The &#8220;Count Inversions&#8221; problem is a great example of how to optimize from brute force to an efficient divide-and-conquer solution. Start with brute force to understand the basics, then use the merge sort approach for best performance.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you\u2019re preparing for coding interviews, the &#8220;Count Inversions&#8221; problem is a classic and important question. In this blog, we\u2019ll explain the problem, walk you through the brute force and optimal solutions, and make everything easy to understand with code comments, dry runs, and clear explanations. Given an array of integers&nbsp;arr[]. Find the&nbsp;Inversion Count&nbsp;in the<\/p>\n","protected":false},"author":1,"featured_media":533,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,5],"tags":[7,18,12],"class_list":{"0":"post-532","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-expert","9":"tag-array","10":"tag-hard","11":"tag-sorting-algos"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/07\/inversions-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/532","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=532"}],"version-history":[{"count":1,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/532\/revisions"}],"predecessor-version":[{"id":534,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/532\/revisions\/534"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/533"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=532"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=532"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=532"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}