{"id":"reverse-pairs","title":"Reverse Pairs","difficulty":"hard","patterns":["sorting-divide-conquer"],"primaryConcept":"sorting-divide-conquer","concepts":["sorting-divide-conquer"],"problemForm":"advanced","companies":["Amazon","Google","Meta","Microsoft"],"category":"searching-sorting","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"nums","sizeMetric":"array-length","sizes":[8,16,32,64],"valueRange":{"min":-50,"max":50}},"description":"Given an integer array `nums`, return the number of reverse pairs.\n\nA reverse pair is a pair of indices `(i, j)` where `i < j` and `nums[i] > 2 * nums[j]`.\n\nFor this TraceCode exercise, use a merge-sort based divide-and-conquer solution. Do not use the O(n^2) nested-loop approach.","requiredComplexity":[{"metric":"time","bound":"O(n log n)","scope":"function","functions":["reversePairs"],"case":"worst","enforcement":"hard","reason":"Each merge-sort level scans and merges the interval in linear time."}],"examples":[{"input":"nums = [1,3,2,3,1]","output":"2","explanation":"The reverse pairs are (3 at index 1, 1 at index 4) and (3 at index 3, 1 at index 4)."},{"input":"nums = [2,4,3,5,1]","output":"3","explanation":"The valid pairs are (4,1), (3,1), and (5,1)."}],"constraints":[{"id":"1-len-nums-50000","text":"1 <= len(nums) <= 50000","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":50000}},{"id":"2-31-nums-i-2-31-1","text":"-2^31 <= nums[i] <= 2^31 - 1","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":-2147483648,"max":2147483647}}],"starterCode":"class Solution:\n    def reversePairs(self, nums: list[int]) -> int:\n        # Your code here\n        pass","functionName":"reversePairs","testCases":[{"id":"1","input":{"nums":[1,3,2,3,1]},"expected":2,"description":"Classic sample with two reverse pairs."},{"id":"2","input":{"nums":[2,4,3,5,1]},"expected":3,"description":"All valid pairs end at the final value."},{"id":"3","input":{"nums":[5,4,3,2,1]},"expected":4,"description":"Descending values produce several but not all possible pairs."},{"id":"4","input":{"nums":[-5,-5]},"expected":1,"description":"Negative values still follow the strict inequality."},{"id":"5","input":{"nums":[2147483647,1073741824,-1]},"expected":2,"description":"Large values require safe doubled comparisons."},{"id":"hidden-1","input":{"nums":[1,1,1]},"expected":0,"description":"Equal values do not satisfy the strict reverse-pair condition."},{"id":"hidden-2","input":{"nums":[10,5,2,1]},"expected":4,"description":"Multiple cross-half pairs share the same right-side values."},{"id":"hidden-3","input":{"nums":[-2,-1,-3]},"expected":2,"description":"Negative right values can make the doubled threshold smaller."},{"id":"hidden-4","input":{"nums":[8,6,4,2,1,3,5,7,9]},"expected":6,"description":"Candidate corpus scenario with interleaved sorted halves."},{"id":"hidden-5","input":{"nums":[9,1,0]},"description":"A small array with one very large leading value.","expected":3},{"id":"public-11","input":{"nums":[0,-1,-2,-3]},"expected":6,"description":"Every earlier value forms a reverse pair against later descending negatives."},{"id":"public-12","input":{"nums":[1,2,4,8,16]},"expected":0,"description":"Strictly increasing powers of two produce no reverse pairs."},{"id":"public-13","input":{"nums":[1000000000,-1000000000,0,-1]},"expected":4,"description":"Boundary-magnitude values exercise doubled comparisons with negatives."},{"id":"public-14","input":{"nums":[6,13,2,5,1]},"expected":6,"description":"Interleaved values create both local and cross-half reverse pairs."}],"hints":[{"level":1,"content":"A direct nested-loop count is too slow. Think about counting pairs while sorting the array."},{"level":2,"content":"After the left and right halves are sorted, a pointer in the right half only moves forward while testing `nums[i] > 2 * nums[j]`."},{"level":3,"content":"Use merge sort. Count cross-half reverse pairs before merging the two sorted halves back together.","revealPattern":true}],"guidedFlow":{"version":2,"progressRevision":"reverse-pairs-2026-11-20-count-across-sorted-halves","approachSelection":{"contract":"approach-selection-v1","question":"Which plan should count the pairs?","decisionPrompt":"A pair depends on which number came first, and the array can hold 50,000 numbers.","approaches":[{"id":"brute-force","name":"Compare every pair","summary":"Compare each number with every number after it.","decisionReason":"It never loses track of which number came first, but 50,000 numbers take about 1.25 billion comparisons.","complexity":{"time":"O(n^2)","space":"O(1)"},"tradeoffs":["About 1.25 billion comparisons for 50,000 numbers, and no extra memory."],"isOptimal":false},{"id":"sort-once","name":"Sort the whole array first","summary":"Put all the numbers in sorted order, then count from the sorted array.","decisionReason":"Sorted, the array reads 1, 2, 5, 6, 13. Every number now comes before every larger one, so counting the sorted array gives 0 where the answer is 6.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["The sort itself is fast, but the sorted array no longer shows which number came first."],"isOptimal":false},{"id":"merge-count","name":"Sort each half on its own","summary":"Cut the array in the middle and sort each half on its own. Count the pairs that have one number in each half, and count the pairs inside each half separately.","decisionReason":"Every number in the left half came before every number in the right half, and sorting inside a half cannot change that. With both halves sorted, one comparison can settle several of those pairs at once.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["A few steps per number at each of about 16 levels of halving for 50,000 numbers, and extra memory as large as the array."],"isOptimal":true}]},"codingCheckpoints":[{"id":"recursive-calls","title":"Cut the range and count each half","description":"Write a helper that counts the pairs in one range of the array. A range of one number has none. Any longer range is cut at its midpoint, the helper runs on both halves, and their two counts are added.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sequence-ordering","fact":"recurses_on_midpoint_split_intervals","scope":"recursive-calls","readMode":"sequence-ordering-value-query-v1"}]},"semanticSpec":{"intent":"Create a merge-sort helper that stops on collapsed intervals, splits by midpoint, and combines the left and right recursive counts.","doneWhen":"This step is done when the helper checks `lo >= hi`, computes `mid`, and accumulates recursive counts from both midpoint-separated intervals.","shouldFailWhen":"This step should fail if only one half recurses, if the midpoint split is missing, or if a collapsed interval does not return zero.","roles":["lower bound","upper bound","midpoint","recursive count"],"mustProve":["The helper uses interval bounds and a midpoint split.","Both halves are processed recursively and their counts are combined."],"mustNotAccept":["Recursing on the original interval again.","Dropping either the left or right recursive count."],"equivalentVariants":["Use a nested merge-sort helper over inclusive interval bounds.","Use any equivalent midpoint interval split that combines both recursive subtotals."],"proofSnippets":[{"id":"py-reverse-pairs-recursive-calls","language":"python","code":"class Solution:\n    def reversePairs(self, nums: list[int]) -> int:\n        def merge_sort(lo: int, hi: int) -> int:\n            if lo >= hi:\n                return 0\n            mid = (lo + hi) // 2\n            count = merge_sort(lo, mid) + merge_sort(mid + 1, hi)\n        return 0"}]},"commonMistakes":["Running the helper on one half only, which loses the pairs inside the other","Cutting so that one half is the whole range again, which never ends"],"hint":"Each half hands back the number of pairs inside it, so the helper gives back a number, and the two numbers start the count for this range."},{"id":"count-cross-pairs","title":"Count the pairs across the cut","description":"Both halves are sorted now. For each number in the left half, move a marker forward through the right half while the left number is more than twice the number under the marker. Then add to the count how many right-half numbers are behind the marker.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"additively_updates_accumulator","scope":"update-total","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Before merging, count pairs where the left value is more than twice values in the sorted right half.","doneWhen":"This step is done when a right-half pointer advances while `nums[i] > 2 * nums[j]` and the number of advanced positions is added to the interval count.","shouldFailWhen":"This step should fail if the code recomputes pairs with nested loops, resets the right pointer for every left value, or forgets to add the cross count.","roles":["left scan","right boundary pointer","reverse-pair threshold","cross-pair count"],"mustProve":["The code scans left-half positions after recursive sorting.","The code accumulates how many right-half positions satisfy the doubled-value inequality."],"mustNotAccept":["Counting `nums[i] > nums[j]` without the doubled threshold.","Overwriting the recursive count instead of adding cross pairs to it."],"equivalentVariants":["Use a single right pointer that only moves forward across the sorted right half.","Use any equivalent cross-half scan that adds the number of valid right values for each left value."],"proofSnippets":[{"id":"py-reverse-pairs-count-cross","language":"python","code":"class Solution:\n    def reversePairs(self, nums: list[int]) -> int:\n        def merge_sort(lo: int, hi: int) -> int:\n            if lo >= hi:\n                return 0\n            mid = (lo + hi) // 2\n            count = merge_sort(lo, mid) + merge_sort(mid + 1, hi)\n            j = mid + 1\n            for i in range(lo, mid + 1):\n                while j <= hi and nums[i] > 2 * nums[j]:\n                    j += 1\n                count += j - (mid + 1)\n        return 0"}]},"commonMistakes":["Testing whether the left number is larger than the right one, when a pair takes more than twice","Putting the marker back at the start for every left number, which repeats comparisons whose results are already known","Counting inside the merge, whose comparison only asks which number is smaller","Doubling a value near 2,147,483,647 in a 32-bit integer"],"hint":"The marker starts on the first number of the right half once, before the first left number. It is never moved back, and it cannot go past the end of the right half."},{"id":"merge-arrays","title":"Merge the halves back into the range","description":"Build one sorted run from the two sorted halves: keep taking the smaller of the two front numbers, copy whatever is left over, and write the run back over the same range of the array.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sequence-ordering","fact":"merges_sorted_intervals_with_writeback","scope":"merge-arrays","readMode":"sequence-ordering-value-query-v1"}]},"semanticSpec":{"intent":"After counting cross pairs, restore sorted order for the current interval so parent calls can count correctly.","doneWhen":"This step is done when the code merges both sorted halves into a temporary buffer, flushes remaining values, and writes the buffer back to the current interval.","shouldFailWhen":"This step should fail if the merge drops values, skips the tail flush, or leaves the interval unsorted for parent calls.","roles":["left sorted interval","right sorted interval","temporary buffer","writeback"],"mustProve":["The merge compares current values from both sorted halves.","The completed buffer is copied back into the same interval."],"mustNotAccept":["Returning a sorted copy without updating the interval used by parent calls.","Merging before the cross-pair count has been accumulated."],"equivalentVariants":["Use a temporary array and copy it back to `nums[lo:hi+1]`.","Use any equivalent stable or unstable sorted merge that preserves every value."],"proofSnippets":[{"id":"py-reverse-pairs-merge-arrays","language":"python","code":"class Solution:\n    def reversePairs(self, nums: list[int]) -> int:\n        def merge_sort(lo: int, hi: int) -> int:\n            if lo >= hi:\n                return 0\n            mid = (lo + hi) // 2\n            count = merge_sort(lo, mid) + merge_sort(mid + 1, hi)\n            j = mid + 1\n            for i in range(lo, mid + 1):\n                while j <= hi and nums[i] > 2 * nums[j]:\n                    j += 1\n                count += j - (mid + 1)\n            temp = []\n            left = lo\n            right = mid + 1\n            while left <= mid and right <= hi:\n                if nums[left] <= nums[right]:\n                    temp.append(nums[left])\n                    left += 1\n                else:\n                    temp.append(nums[right])\n                    right += 1\n            while left <= mid:\n                temp.append(nums[left])\n                left += 1\n            while right <= hi:\n                temp.append(nums[right])\n                right += 1\n            for k in range(len(temp)):\n                nums[lo + k] = temp[k]\n        return 0"}]},"commonMistakes":["Stopping when one half runs out, which loses the numbers still waiting in the other","Building the merged run and never writing it back over the range"],"hint":"The level above makes its pass over this range as one of its sorted halves, so the range itself has to end up sorted."},{"id":"return-total","title":"Return the total","description":"The helper returns its count for the range it was given, and the function returns the helper's count for the whole array.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_terminal_accumulator","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Return the count accumulated from left-half, right-half, and cross-half reverse pairs.","doneWhen":"This step is done when each helper call returns its accumulated count and the public method returns the count for the full interval.","shouldFailWhen":"This step should fail if the method returns the sorted array, the last merge buffer, or only the cross-half subtotal.","roles":["recursive subtotal","cross-pair count","final return"],"mustProve":["The helper returns the accumulated count after merge writeback.","The outer method returns the helper result for the whole array."],"mustNotAccept":["Returning `nums` after it has been sorted.","Returning only the final interval's cross count without recursive subtotals."],"equivalentVariants":["Return `count` from the helper and return the helper call over the full interval.","Use any equivalent recursive count return that includes all subintervals."],"proofSnippets":[{"id":"py-reverse-pairs-return-total","language":"python","code":"class Solution:\n    def reversePairs(self, nums: list[int]) -> int:\n        def merge_sort(lo: int, hi: int) -> int:\n            if lo >= hi:\n                return 0\n            mid = (lo + hi) // 2\n            count = merge_sort(lo, mid) + merge_sort(mid + 1, hi)\n            j = mid + 1\n            for i in range(lo, mid + 1):\n                while j <= hi and nums[i] > 2 * nums[j]:\n                    j += 1\n                count += j - (mid + 1)\n            temp = []\n            left = lo\n            right = mid + 1\n            while left <= mid and right <= hi:\n                if nums[left] <= nums[right]:\n                    temp.append(nums[left])\n                    left += 1\n                else:\n                    temp.append(nums[right])\n                    right += 1\n            while left <= mid:\n                temp.append(nums[left])\n                left += 1\n            while right <= hi:\n                temp.append(nums[right])\n                right += 1\n            for k in range(len(temp)):\n                nums[lo + k] = temp[k]\n            return count\n        return merge_sort(0, len(nums) - 1)"}]},"commonMistakes":["Returning the sorted array, which is only a by-product","Returning the pairs across the cut without the counts from the two halves"],"hint":"A range's count already holds the counts of both its halves and the pairs across its cut."}],"slides":[{"id":"read-the-problem","kind":"info","title":"Count the pairs where an earlier number is more than twice a later one","workspacePanel":"problem","body":["You are given an array of integers. Take any two positions in it: they form a reverse pair when the number at the earlier position is more than twice the number at the later one.","The function returns how many reverse pairs the array holds."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pair-6-2","title":"6 and 2 are a reverse pair","summary":"6 comes first, and 6 is more than 2 × 2 = 4.","state":{"nums":[6,13,2,5,1],"i":0,"j":2,"labels":{"i":"earlier","j":"later"}}},{"id":"no-pair-2-1","title":"2 and 1 are not","summary":"2 is exactly 2 × 1, and exactly twice is not enough.","state":{"nums":[6,13,2,5,1],"i":2,"j":4,"labels":{"i":"earlier","j":"later"}}},{"id":"no-pair-2-5","title":"Neither are 2 and 5","summary":"5 is more than 2 × 2 = 4, but 5 comes later. Only the earlier number can be the one that is more than twice the other.","state":{"nums":[6,13,2,5,1],"i":2,"j":3,"labels":{"i":"earlier","j":"later"}}},{"id":"six-pairs","title":"This array has six","summary":"The pairs are 6 with 2, 6 with 1, 13 with 2, 13 with 5, 13 with 1, and 5 with 1. For this array the function returns 6.","state":{"nums":[6,13,2,5,1]}}]}},{"id":"brute-force","kind":"code-trace","title":"The direct way compares every pair","workspacePanel":"trace","body":["Take each number in turn and compare it with every number after it."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"count = 0\nfor i in range(len(nums)):\n    for j in range(i + 1, len(nums)):\n        if nums[i] > 2 * nums[j]:\n            count += 1\nreturn count","steps":[{"id":"scan-from-6","title":"6 is compared with 13, 2, 5 and 1","codeLine":4,"summary":"Four comparisons find two pairs: 6 with 2 and 6 with 1.","state":{"nums":[6,13,2,5,1],"i":0,"j":4,"count":2,"comparisons":4}},{"id":"scan-from-13","title":"13 is compared with 2, 5 and 1","codeLine":4,"summary":"Three comparisons, and each one is a pair. The count is 5.","state":{"nums":[6,13,2,5,1],"i":1,"j":4,"count":5,"comparisons":7}},{"id":"scan-from-2","title":"2 is compared with 5 and 1","codeLine":4,"summary":"Two comparisons find no pair, and the count stays at 5.","state":{"nums":[6,13,2,5,1],"i":2,"j":4,"count":5,"comparisons":9}},{"id":"scan-from-5","title":"5 is compared with 1","codeLine":4,"summary":"One comparison finds the last pair, and the count is 6.","state":{"nums":[6,13,2,5,1],"i":3,"j":4,"count":6,"comparisons":10}},{"id":"scan-done","title":"The scan returns 6","codeLine":6,"summary":"Five numbers took 4 + 3 + 2 + 1 = 10 comparisons.","state":{"nums":[6,13,2,5,1],"count":6,"comparisons":10}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let count = 0;\nfor (let i = 0; i < nums.length; i++) {\n    for (let j = (i + 1); j < nums.length; j++) {\n        if (nums[i] > (2 * nums[j])) {\n            count++;\n        }\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":9},"statementBundles":{"5":{"startLine":5,"endLine":8}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let count = 0;\nfor (let i = 0; i < nums.length; i++) {\n    for (let j = (i + 1); j < nums.length; j++) {\n        if (nums[i] > (2 * nums[j])) {\n            count++;\n        }\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":9},"statementBundles":{"5":{"startLine":5,"endLine":8}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int count = 0;\nfor (int i = 0; i < nums.size(); i++) {\n    for (int j = (i + 1); j < nums.size(); j++) {\n        if (nums.get(i) > (2 * nums.get(j))) {\n            count++;\n        }\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":9},"statementBundles":{"5":{"startLine":5,"endLine":8}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int count = 0;\nfor (int i = 0; i < nums.Count; i++) {\n    for (int j = i + 1; j < nums.Count; j++) {\n        if (nums[i] > 2 * nums[j]) {\n            count++;\n        }\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":9},"statementBundles":{"5":{"startLine":5,"endLine":8}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int count = 0;\nfor (int i = 0; i < nums.size(); i++) {\n    for (int j = (i + 1); j < nums.size(); j++) {\n        if (nums[i] > (2 * nums[j])) {\n            count++;\n        }\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":9},"statementBundles":{"5":{"startLine":5,"endLine":8}}}}}},{"id":"waste-probe","kind":"case-probe","title":"Five numbers took 10 comparisons, and the array can hold 50,000. About how many would that take?","workspacePanel":"trace","options":[{"id":"about-fifty-thousand","label":"About 50,000","rationale":"One comparison per number would give 50,000. The trace already spent four comparisons on 6 alone.","isCorrect":false},{"id":"about-hundred-thousand","label":"About 100,000","rationale":"That assumes the work grows in step with the length: five numbers took 10 comparisons, so 50,000 would take 100,000. Each number is compared with every number after it, though, and the first one alone needs 49,999.","isCorrect":false},{"id":"about-one-and-a-quarter-billion","label":"About 1.25 billion","rationale":"The first number is compared with 49,999 others, the next with 49,998, and so on down to 1. That adds up to 50,000 × 49,999 / 2 = 1,249,975,000.","isCorrect":true}]},{"id":"cross-count-discovery","kind":"case-probe","title":"Suppose the three numbers after 13 are put in sorted order, and the first two are covered. 13 is more than twice 5. What does that say about the covered two?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"after-13-sorted","state":{"arrays":[{"name":"after 13, sorted","values":["?","?",5],"current":2}]}}]},"options":[{"id":"depends-on-values","label":"It depends on what the covered numbers are","rationale":"Sorted order already says enough. Whatever they are, they come before 5, so neither is larger than 5.","isCorrect":false},{"id":"more-than-twice-them-too","label":"13 is more than twice each of them","rationale":"They come before 5 in sorted order, so neither is larger than 5, and 13 is more than 2 × 5 = 10. In a sorted run, the numbers 13 pairs with sit together at the front, so counting them comes down to finding where that front part ends.","isCorrect":true},{"id":"only-later-numbers","label":"Nothing, because the comparison with 5 only settles numbers after 5","rationale":"The numbers before 5 are the settled ones. A number after 5 can still fail: 13 is less than 2 × 7 = 14, so a 7 would.","isCorrect":false}]},{"id":"approach-selection","kind":"choice","source":"approach-selection","title":"Which plan should count the pairs?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"example-array","state":{"nums":[6,13,2,5,1]}}]}},{"id":"inside-pairs-probe","kind":"case-probe","title":"6 and 2 are a pair, and both are in the left half. How should pairs inside a half be counted?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"halves-as-given","state":{"arrays":[{"name":"left half","values":[6,13,2]},{"name":"right half","values":[5,1]}]}}]},"options":[{"id":"after-sorting-the-half","label":"After the half is sorted, from 2, 6, 13","rationale":"Sorted, the half reads 2, 6, 13. Nothing shows that 2 came after 6 and 13, so the pairs inside the half can no longer be found.","isCorrect":false},{"id":"same-plan-on-the-half","label":"Before the half is sorted, by running the same plan on it","rationale":"The half 6, 13, 2 is an array in its own right. Cut it into [6, 13] and [2], and the pairs 6 with 2 and 13 with 2 are the ones across that smaller cut. The same plan runs on each half, then on the halves of those.","isCorrect":true},{"id":"every-pair-in-the-half","label":"Before the half is sorted, by comparing every pair in it","rationale":"A half of 25,000 numbers still means about 312 million comparisons.","isCorrect":false}]},{"id":"dry-run-setup","kind":"info","title":"Each half comes back sorted, with its own pairs counted","workspacePanel":"visualizer","body":["Suppose both halves have run the plan. The left half 6, 13, 2 counted the 2 pairs inside it and now reads 2, 6, 13. The right half 5, 1 counted its 1 pair and now reads 1, 5.","The pairs still uncounted have one number in each half. To count them, make one pass over the left numbers, smallest first. A marker, `j`, starts on the first right number. For each left number, the marker moves forward while that left number is more than twice the number under it."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"halves-sorted","state":{"arrays":[{"name":"left half","values":[2,6,13]},{"name":"right half","values":[1,5],"j":0}],"across the cut":0}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Count the pairs across the cut","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pass-start","state":{"arrays":[{"name":"left half","values":[2,6,13],"i":0},{"name":"right half","values":[1,5],"j":0}],"across the cut":0}},{"id":"after-2","state":{"arrays":[{"name":"left half","values":[2,6,13],"i":1},{"name":"right half","values":[1,5],"j":0}],"across the cut":0}},{"id":"after-6","state":{"arrays":[{"name":"left half","values":[2,6,13],"i":1},{"name":"right half","values":[1,5],"j":1,"used":[0]}],"across the cut":1}},{"id":"13-starts","state":{"arrays":[{"name":"left half","values":[2,6,13],"i":2},{"name":"right half","values":[1,5],"j":1,"used":[0]}],"across the cut":1}},{"id":"after-13","state":{"arrays":[{"name":"left half","values":[2,6,13],"i":2},{"name":"right half","values":[1,5],"used":[0,1]}],"across the cut":3}}]},"beats":[{"id":"two-against-one","title":"2 is the first left number. Does it move the marker?","options":[{"id":"yes-larger","label":"Yes, because 2 is larger than 1","rationale":"Being larger is not enough. 2 would have to be more than 2 × 1 = 2.","isCorrect":false},{"id":"no-exactly-twice","label":"No, because 2 is exactly twice 1","rationale":"The rule is more than twice. The marker stays on 1, no right number is behind it, and 2 adds 0 pairs.","isCorrect":true},{"id":"yes-twice-counts","label":"Yes, because twice as large is enough","rationale":"A pair takes more than twice. At exactly twice, 2 and 1 are not a pair.","isCorrect":false}]},{"id":"six-stops-on-five","title":"Where does the marker stop for the next left number, 6?","options":[{"id":"stops-on-1","label":"On 1, where it started","rationale":"6 is more than 2 × 1 = 2, so the marker moves past 1.","isCorrect":false},{"id":"stops-on-5","label":"On 5","rationale":"6 is more than 2 × 1 = 2, so the marker moves past 1. 6 is less than 2 × 5 = 10, so it stops on 5. One right number is now behind the marker, so 6 adds 1 pair.","isCorrect":true},{"id":"stops-off-the-end","label":"Past 5, off the end","rationale":"That would take 6 being more than 2 × 5 = 10.","isCorrect":false}]},{"id":"thirteen-starts-on-five","title":"Where does the marker start for the last left number, 13?","options":[{"id":"starts-on-5","label":"On 5, where 6 left it","rationale":"13 is larger than 6, so it is more than twice the 1 as well, and only 5 is still open. Each left number is at least as large as the one before it, so the marker never has to move back.","isCorrect":true},{"id":"starts-on-1","label":"Back on 1, the first right number","rationale":"That compares 13 with 1 again, and the result is already known: 6 was more than twice 1, and 13 is larger than 6.","isCorrect":false},{"id":"starts-past-5","label":"Past 5, one step further than 6 got","rationale":"Nothing has compared 13 with 5 yet, so the marker cannot skip it.","isCorrect":false}]},{"id":"thirteen-adds-two","title":"13 is more than twice 5, so the marker moves off the end. How many pairs does 13 add?","options":[{"id":"adds-0","label":"0","rationale":"The marker running off the end means 13 is more than twice every right number, so all of them count.","isCorrect":false},{"id":"adds-1","label":"1","rationale":"The marker moved one step for 13, but 13 also pairs with the 1 that was already behind it.","isCorrect":false},{"id":"adds-2","label":"2","rationale":"Both right numbers are behind the marker now: 13 pairs with 5, and with the 1 the marker passed for 6. The pass ends with 0 + 1 + 2 = 3 pairs across the cut.","isCorrect":true}]}]},{"id":"sweep-cost-probe","kind":"case-probe","title":"Back at full size, with 25,000 numbers in each half, at most how many times can the marker move?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pass-finished","state":{"arrays":[{"name":"left half","values":[2,6,13],"i":2},{"name":"right half","values":[1,5],"used":[0,1]}],"across the cut":3}}]},"options":[{"id":"moves-25000","label":"25,000 times","rationale":"The marker only moves forward, and the right half has 25,000 numbers for it to move past. Each left number is visited once as well, so the whole pass takes about 50,000 steps.","isCorrect":true},{"id":"moves-50000","label":"50,000 times","rationale":"The marker moves through the right half only, which holds 25,000 numbers. The other 25,000 are the left numbers.","isCorrect":false},{"id":"moves-625-million","label":"625 million times","rationale":"That is 25,000 × 25,000, one move for every left number with every right number. It would take the marker going back to the start for each left number.","isCorrect":false}]},{"id":"unsorted-half-probe","kind":"case-probe","title":"Suppose the left half had come back unsorted, as 6, 13, 2. What does the pass add when it reaches 2?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"unsorted-left","state":{"arrays":[{"name":"left half","values":[6,13,2],"i":2},{"name":"right half","values":[1,5],"used":[0,1]}],"across the cut":3}}]},"options":[{"id":"adds-none","label":"0 pairs","rationale":"0 is how many pairs 2 really has. The pass never compares 2 with 1, though: it adds whatever is behind the marker, and 13 has already pushed it past both right numbers.","isCorrect":false},{"id":"adds-one","label":"1 pair","rationale":"The marker is past both right numbers by the time 2 arrives, and it never moves back, so 2 is given both.","isCorrect":false},{"id":"adds-two","label":"2 pairs","rationale":"6 and 13 push the marker past both right numbers before 2 arrives. 2 is given 2 pairs it does not have, and the pass ends at 5 where the true count is 3. The pass only works when the left numbers arrive smallest first.","isCorrect":true}]},{"id":"merge-run","kind":"dry-run","source":"trace-example","title":"So each half has to hand back its numbers sorted. Merge the two sorted halves into one run.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"merge-start","state":{"arrays":[{"name":"left half","values":[2,6,13]},{"name":"right half","values":[1,5]},{"name":"merged","values":[]}]}},{"id":"took-1","state":{"arrays":[{"name":"left half","values":[2,6,13],"current":0},{"name":"right half","values":[1,5],"current":1,"used":[0]},{"name":"merged","values":[1]}]}},{"id":"right-used-up","state":{"arrays":[{"name":"left half","values":[2,6,13],"current":1,"used":[0]},{"name":"right half","values":[1,5],"used":[0,1]},{"name":"merged","values":[1,2,5]}]}},{"id":"merge-done","state":{"arrays":[{"name":"left half","values":[2,6,13],"used":[0,1,2]},{"name":"right half","values":[1,5],"used":[0,1]},{"name":"merged","values":[1,2,5,6,13]}]}}]},"beats":[{"id":"smallest-is-a-front","title":"The two sorted halves have to become one sorted run. Where can its smallest number be?","options":[{"id":"front-of-a-half","label":"At the front of one of the halves: 2 or 1","rationale":"Each half is sorted, so its front number is its smallest. The smallest of all five is the smaller of those two fronts, which is 1. After 1 is taken, the next number comes from comparing the new fronts, 2 and 5.","isCorrect":true},{"id":"anywhere-in-right","label":"Anywhere in the right half","rationale":"The right half is sorted, so nothing in it is smaller than its front number, 1.","isCorrect":false},{"id":"anywhere-in-either","label":"Anywhere in either half","rationale":"Both halves are sorted, so only their front numbers can be the smallest.","isCorrect":false}]},{"id":"merge-is-not-the-count","title":"The merge put 1 ahead of 2, 6 and 13, which were all waiting. Is each of them a pair with 1?","options":[{"id":"all-three","label":"Yes, all three","rationale":"All three are larger than 1 and came before it, but 2 is exactly 2 × 1, and exactly twice is not a pair.","isCorrect":false},{"id":"six-and-thirteen-only","label":"6 and 13 are, 2 is not","rationale":"Waiting behind 1 only takes being larger than 1, but a pair takes more than twice, and 2 is exactly 2 × 1. So the comparison that picks the next value cannot do the counting. The count is its own pass with the more-than-twice test, made before the merge while the two halves are still apart.","isCorrect":true},{"id":"none-of-them","label":"No, none of them","rationale":"6 and 13 are each more than 2 × 1 = 2, and both came before 1.","isCorrect":false}]},{"id":"leftover-numbers","title":"The merge takes 2, then 5, and the right half is used up. 6 and 13 are still waiting. What happens to them?","options":[{"id":"compared-first","label":"They are compared with each other first","rationale":"The left half was sorted before the merge began, so 6 and 13 are already in order.","isCorrect":false},{"id":"dropped","label":"They are dropped, because the merge ends when one half runs out","rationale":"The merged run would hold 1, 2, 5 and the array would lose 6 and 13.","isCorrect":false},{"id":"copied-across","label":"They are copied across as they stand","rationale":"6 and 13 are already in order, and both are at least as large as everything already merged. The finished run 1, 2, 5, 6, 13 is then written back over the positions the two halves came from.","isCorrect":true}]}]},{"id":"left-half-run","kind":"info","title":"Each half runs the whole plan on itself","workspacePanel":"visualizer","body":["The left half went in as 6, 13, 2 and came back as 2, 6, 13 with a count of 2."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cut-left-half","title":"6, 13, 2 is cut into 6, 13 and 2","summary":"Each of those two halves runs the plan before anything is counted across the cut between them.","state":{"nums":[6,13,2,5,1],"left":0,"right":2,"labels":{"left":"","right":""}}},{"id":"cut-6-13","title":"6, 13 is cut into 6 and 13","summary":"A single number has no pairs inside it and is already sorted, so 6 and 13 each hand back 0.","state":{"nums":[6,13,2,5,1],"left":0,"right":1,"labels":{"left":"","right":""}}},{"id":"pass-6-13","title":"6 is not more than twice 13","summary":"No pair crosses this cut, and merging 6 with 13 leaves them where they are. The half 6, 13 hands back 0.","state":{"nums":[6,13,2,5,1],"left":0,"right":1,"i":0,"j":1,"labels":{"left":"","right":""}}},{"id":"pass-6-13-2","title":"6 is more than twice 2, and so is 13","summary":"The other half, 2, is a single number and hands back 0. In the pass across this cut, the marker moves past 2 for 6, and for 13 the 2 is already behind it, which makes 2 pairs.","state":{"nums":[6,13,2,5,1],"left":0,"right":2,"i":0,"j":2,"labels":{"left":"","right":""}}},{"id":"merge-6-13-2","title":"The merge takes 2, then copies 6 and 13","summary":"Those three positions now read 2, 6, 13, and the left half hands back 0 + 0 + 2 = 2.","state":{"nums":[2,6,13,5,1],"left":0,"right":2,"labels":{"left":"","right":""}}},{"id":"right-half-done","title":"The right half 5, 1 runs the same way","summary":"5 is more than twice 1, so the right half hands back 1 and leaves its two positions reading 1, 5.","state":{"nums":[2,6,13,1,5],"left":3,"right":4,"labels":{"left":"","right":""}}}]}},{"id":"total-probe","kind":"case-probe","title":"What does the function return for the whole array?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"three-counts","state":{"arrays":[{"name":"left half","values":[2,6,13]},{"name":"right half","values":[1,5]}],"inside the left half":2,"inside the right half":1,"across the cut":3}}]},"options":[{"id":"returns-3","label":"3","rationale":"3 is only the pairs across the cut. 6 with 2, 13 with 2 and 5 with 1 each lie inside one half and would be lost.","isCorrect":false},{"id":"returns-5","label":"5","rationale":"That is the left half's 2 and the 3 across the cut. 5 with 1, inside the right half, counts too.","isCorrect":false},{"id":"returns-6","label":"6","rationale":"2 + 1 + 3 = 6. Every pair lies inside the left half, inside the right half, or across the cut, so the three counts cover each pair exactly once.","isCorrect":true}]},{"id":"edge-case-intro","kind":"info","title":"The comparison also has to hold for negative numbers and very large ones","workspacePanel":"visualizer","body":["Every number so far has been small and positive. The array can also hold negative numbers, and numbers as large as 2,147,483,647.","Both test the one comparison the count is built on: whether one number is more than twice another."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"large-and-negative","state":{"nums":[2147483647,1073741824,-1]}}]}},{"id":"negative-values-probe","kind":"case-probe","title":"First, a negative case: the array -5, -5. Do the two numbers form a pair?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-negatives","state":{"nums":[-5,-5],"i":0,"j":1}}]},"options":[{"id":"no-equal","label":"No, because the numbers are equal","rationale":"Equal positive numbers never form a pair: 5 is less than 2 × 5 = 10. For -5 the doubled value is -10, which is less than -5.","isCorrect":false},{"id":"no-needs-positive","label":"No, because a pair takes positive numbers","rationale":"The rule compares one number with twice another and says nothing about sign.","isCorrect":false},{"id":"yes-more-than-twice","label":"Yes, because -5 is more than twice -5","rationale":"Twice -5 is -10, and -5 is more than -10. Doubling a negative number makes it smaller, so two equal negative numbers always form a pair. The pass still works: a smaller right number has a smaller double, so a left number's pairs still sit at the front of the sorted right half.","isCorrect":true}]},{"id":"overflow-probe","kind":"case-probe","title":"Then a very large case: the right number is 1,073,741,824. What does the comparison need?","summary":"Twice 1,073,741,824 is 2,147,483,648, one more than a signed 32-bit integer can hold.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"large-values","state":{"nums":[2147483647,1073741824,-1],"i":0,"j":1}}]},"options":[{"id":"wider-type","label":"The doubling done in a wider integer type","rationale":"In 64 bits the product is 2,147,483,648, and 2,147,483,647 is less than it, so these two numbers are not a pair. Where the number type already holds values this large, the comparison works as written.","isCorrect":true},{"id":"nothing-needed","label":"Nothing, because an overflowing product still compares correctly","rationale":"A 32-bit product cannot hold 2,147,483,648. It typically wraps around to -2,147,483,648, and then 2,147,483,647 is counted as a pair with 1,073,741,824 when it is not.","isCorrect":false},{"id":"halve-the-left","label":"Halving the left number with integer division instead","rationale":"Integer division drops the remainder. 5 is more than twice 2, but 5 halved is 2, which is not more than 2, so that pair would be lost.","isCorrect":false}]},{"id":"ready-to-code","kind":"info","title":"Each half counts its own pairs, and one pass counts the rest","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["The function counts the pairs in one range of the array. A range of one number has none. A longer range is cut in the middle, and each half counts its own pairs and comes back sorted.","Then one pass with the marker counts the pairs across the cut, and the two halves are merged into one sorted run written back over the range.","The range's count is those three counts added together. For the whole array, that is the answer."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"example-array-again","state":{"nums":[6,13,2,5,1]}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Count the pairs while sorting","workspacePanel":"code"},{"id":"complete","kind":"complete","title":"Reverse pairs from sorted halves","workspacePanel":"code","takeaways":[{"title":"A cut keeps the order a pair depends on","body":"Every number in the left half came before every number in the right half, however each half is ordered inside. Sorting the halves separately loses nothing that a pair across the cut needs."},{"title":"One forward marker counts across the cut","body":"With both halves sorted, each left number adds the right numbers behind the marker, and the marker never moves back. This pass has its own comparison, more than twice, and runs before the merge."},{"title":"Each range returns three counts added together","body":"A range adds the pairs inside its left half, the pairs inside its right half and the pairs across its cut. Then it merges its numbers into sorted order, so the level above can make its own pass."},{"title":"O(n log n) time and O(n) space","body":"The array can be halved about log n times, 16 for 50,000 numbers. At each depth, every pass moves through each half once and every merge writes each number into the run and back, so one depth costs O(n). The merge buffer takes O(n) extra space. Comparing every pair is O(n^2), about 1.25 billion comparisons at that size."}]}],"slidesOrigin":"authored"}}
