{"id":535,"date":"2025-07-07T19:26:16","date_gmt":"2025-07-07T13:56:16","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=535"},"modified":"2025-07-07T19:26:17","modified_gmt":"2025-07-07T13:56:17","slug":"reverse-pairs","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/reverse-pairs\/","title":{"rendered":"Reverse Pairs | Leetcode 493 | Optimal Merge Sort"},"content":{"rendered":"\n<p>The &#8220;Reverse Pairs&#8221; problem is a popular and challenging interview question. In this blog, we\u2019ll explain the problem, walk you through both 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 integer array&nbsp;<code>nums<\/code>, return&nbsp;<em>the number of&nbsp;<strong>reverse pairs<\/strong>&nbsp;in the array<\/em>.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/reverse-pairs\/description\/\" 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<p>A&nbsp;<strong>reverse pair<\/strong>&nbsp;is a pair&nbsp;<code>(i, j)<\/code>&nbsp;where:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>0 &lt;= i &lt; j &lt; nums.length<\/code>\u00a0and<\/li>\n\n\n\n<li><code>nums[i] > 2 * nums[j]<\/code>.<\/li>\n<\/ul>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> nums = [1,3,2,3,1]<br><strong>Output:<\/strong> 2<br><strong>Explanation:<\/strong> The reverse pairs are:<br>(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1<br>(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> nums = [2,4,3,5,1]<br><strong>Output:<\/strong> 3<br><strong>Explanation:<\/strong> The reverse pairs are:<br>(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1<br>(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1<br>(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4<\/sup><\/code><\/li>\n\n\n\n<li><code>-2<sup>31<\/sup> &lt;= nums[i] &lt;= 2<sup>31<\/sup> - 1<\/code><\/li>\n<\/ul>\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-3b8a5c7a-04e7-4795-98a0-6add605a9a20\" 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\/reverse-pairs\/#0-brute-force-solution-nested-loops\" style=\"\">Brute Force Solution (Nested Loops)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/reverse-pairs\/#1-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/reverse-pairs\/#2-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/reverse-pairs\/#3-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/reverse-pairs\/#4-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/reverse-pairs\/#5-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/reverse-pairs\/#6-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/reverse-pairs\/#7-optimal-solution-merge-sort-approach\" style=\"\">Optimal Solution (Merge Sort Approach)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/reverse-pairs\/#8-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/reverse-pairs\/#9-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/reverse-pairs\/#10-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/reverse-pairs\/#11-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/reverse-pairs\/#12-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/reverse-pairs\/#13-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/reverse-pairs\/#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 most straightforward 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 Reverse Pairs:<\/strong><br>If\u00a0<code>nums[i] > 2 * nums[j]<\/code>, count it as a reverse pair.<\/li>\n\n\n\n<li><strong>Why does this work?<\/strong><br>We check all possible pairs, so we count every reverse pair.<\/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(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\n\nclass Solution:\n    def reversePairs(self, nums: List[int]) -&gt; int:\n        count = 0\n        n = len(nums)\n        for i in range(0, n):\n            for j in range(i + 1, n):\n                if nums[i] &gt; 2 * nums[j]:      # check reverse pair condition\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: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> typing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> List<\/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\">reversePairs<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/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: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)<\/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\"> nums[i] &gt; <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\"> * nums[j]:      <\/span><span style=\"color: #6A9955\"># check reverse pair condition<\/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\u00a0<code>nums[i] > 2 * nums[j]<\/code>.<\/li>\n\n\n\n<li>If true, we increment the reverse pair 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>nums = [1][1]<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>(1,3): 1 > 6? No<\/li>\n\n\n\n<li>(1,2): 1 > 4? No<\/li>\n\n\n\n<li>(1,3): 1 > 6? No<\/li>\n\n\n\n<li>(1,1): 1 > 2? No<\/li>\n\n\n\n<li>(3,2): 3 > 4? No<\/li>\n\n\n\n<li>(3,3): 3 > 6? No<\/li>\n\n\n\n<li>(3,1): 3 > 2? Yes (count = 1)<\/li>\n\n\n\n<li>(2,3): 2 > 6? No<\/li>\n\n\n\n<li>(2,1): 2 > 2? No<\/li>\n\n\n\n<li>(3,1): 3 > 2? Yes (count = 2)<\/li>\n<\/ul>\n\n\n\n<p><strong>Final count:<\/strong><br><code>2<\/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 reverse pairs 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 Reverse Pairs During Merge:<\/strong><br>While merging two sorted halves, for each element in the left half, count how many elements in the right half satisfy the reverse pair condition.<\/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 reverse pairs 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        count = 0\n        result = []\n        j = 0\n        # Count reverse pairs\n        for i in range(0, n):\n            while j &lt; m and arr1[i] &gt; 2 * arr2[j]:\n                j += 1\n            count += j\n\n        i, j = 0, 0\n        # Merge two sorted arrays\n        while i &lt; n and j &lt; m:\n            if arr1[i] &lt;= arr2[j]:\n                result.append(arr1[i])\n                i += 1\n            else:\n                result.append(arr2[j])\n                j += 1\n\n        while i &lt; n:\n            result.append(arr1[i])\n            i += 1\n        while j &lt; m:\n            result.append(arr2[j])\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\n\n        mid = len(lst) \/\/ 2\n        first_half = lst[:mid]\n        second_half = lst[mid:]\n\n        fh, cnt1 = self.mergeSort(first_half)\n        sh, cnt2 = self.mergeSort(second_half)\n\n        merged, count = self.mergeList(fh, sh)\n        return merged, cnt1 + cnt2 + count\n\n    def reversePairs(self, nums: List[int]) -&gt; int:\n        m, c = self.mergeSort(nums)\n        return c\" 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\">        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 style=\"color: #D4D4D4\">        j = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Count reverse pairs<\/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\">while<\/span><span style=\"color: #D4D4D4\"> j &lt; m <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> arr1[i] &gt; <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\"> * arr2[j]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                j += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            count += j<\/span><\/span>\n<span class=\"line\"><\/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\">        <\/span><span style=\"color: #6A9955\"># Merge two sorted arrays<\/span><\/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>\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\">                result.append(arr2[j])<\/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>\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>\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>\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>\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>\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>\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\">reversePairs<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/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\">        m, c = <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.mergeSort(nums)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> c<\/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, for each element in the left half, we count how many elements in the right half satisfy\u00a0<code>arr1[i] > 2 * arr2[j]<\/code>.<\/li>\n\n\n\n<li>We merge the two halves as in standard merge sort.<\/li>\n\n\n\n<li>We sum up the counts from all recursive calls.<\/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>nums = [1][1]<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Split into\u00a0<code>[1]<\/code>\u00a0and\u00a0<code>[1]<\/code><\/li>\n\n\n\n<li><code>[1]<\/code>\u00a0\u2192\u00a0<code>[1]<\/code>, &#8220;<\/li>\n\n\n\n<li><code>[1]<\/code>\u00a0\u2192\u00a0<code>, `[1]` \u2192\u00a0<\/code>,\u00a0<code>[1]<\/code><\/li>\n\n\n\n<li>Merge &#8220; and\u00a0<code>[1]<\/code>: check 3 > 2*1? Yes (count = 1)<\/li>\n\n\n\n<li>Merge &#8220; and\u00a0<code>[1]<\/code>: check 2 > 2<em>1? No; 2 > 2<\/em>3? No<\/li>\n\n\n\n<li>Merge\u00a0<code>[1]<\/code>\u00a0and\u00a0<code>[1]<\/code>: count reverse pairs across the two halves<\/li>\n\n\n\n<li>Total count = 2<\/li>\n<\/ul>\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;Reverse Pairs&#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>The &#8220;Reverse Pairs&#8221; problem is a popular and challenging interview question. In this blog, we\u2019ll explain the problem, walk you through both brute force and optimal solutions, and make everything easy to understand with code comments, dry runs, and clear explanations. Given an integer array&nbsp;nums, return&nbsp;the number of&nbsp;reverse pairs&nbsp;in the array. Here&#8217;s the [Problem Link]<\/p>\n","protected":false},"author":1,"featured_media":536,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,5],"tags":[7,18,12],"class_list":{"0":"post-535","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\/reverse-pairs-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\/535","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=535"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/535\/revisions"}],"predecessor-version":[{"id":562,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/535\/revisions\/562"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/536"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=535"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=535"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=535"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}