{"id":"count-inversions","title":"Count Inversions","difficulty":"medium","patterns":["sorting-divide-conquer"],"primaryConcept":"sorting-divide-conquer","concepts":["sorting-divide-conquer"],"problemForm":"core","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 inversions.\n\nAn inversion is a pair of indices `(i, j)` where `i < j` and `nums[i] > nums[j]`.\n\nYour solution should run in O(n log n) time.","requiredComplexity":[{"metric":"time","bound":"O(n log n)","scope":"function","functions":["countInversions"],"case":"worst","enforcement":"hard","reason":"Each merge-sort level counts cross-half inversions and merges the interval in linear time."}],"examples":[{"input":"nums = [2,4,1,3,5]","output":"3","explanation":"The inversions are (2,1), (4,1), and (4,3)."},{"input":"nums = [5,4,3,2,1]","output":"10","explanation":"Every pair is inverted in a descending array of length 5."}],"constraints":[{"id":"1-len-nums-10-5","text":"1 <= len(nums) <= 10^5","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":100000}},{"id":"10-9-nums-i-10-9","text":"-10^9 <= nums[i] <= 10^9","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":-1000000000,"max":1000000000}},{"id":"the-answer-is-guaranteed-to-fit-in-a-32-bit-integer","text":"The answer is guaranteed to fit in a 32-bit integer","check":{"kind":"guarantee","guarantee":"resultRange","min":-2147483648,"max":2147483647}}],"starterCode":"class Solution:\n    def countInversions(self, nums: list[int]) -> int:\n        # Your code here\n        pass","functionName":"countInversions","testCases":[{"id":"1","input":{"nums":[2,4,1,3,5]},"expected":3,"description":"Classic mixed-order sample."},{"id":"2","input":{"nums":[5,4,3,2,1]},"expected":10,"description":"Every pair is inverted."},{"id":"3","input":{"nums":[1,2,3,4]},"expected":0,"description":"Already sorted ascending."},{"id":"4","input":{"nums":[1,3,2,3,1]},"expected":4,"description":"Duplicates only count when the left value is strictly greater."},{"id":"5","input":{"nums":[2,2,1]},"expected":2,"description":"Equal values are not inversions."},{"id":"6","input":{"nums":[-1,-2,-3]},"expected":3,"description":"Negative values still use the same ordering rule."},{"id":"7","input":{"nums":[1]},"expected":0,"description":"One value cannot form a pair."},{"id":"h1","input":{"nums":[4,1,3,2]},"description":"A large prefix value creates several cross-position inversions.","expected":4},{"id":"h2","input":{"nums":[3,3,2,2,1]},"description":"Duplicate descending tail creates many pairs.","expected":8},{"id":"h3","input":{"nums":[1,1,1,1]},"description":"Equal values never count as inversions.","expected":0},{"id":"h4","input":{"nums":[2,3,8,6,1]},"description":"Five pairs are inverted in an array that is neither sorted nor reversed.","expected":5},{"id":"h5","input":{"nums":[-1,-3,-2,0]},"description":"Negative values compare normally when counting inversions.","expected":2}],"hints":[{"level":1,"content":"An inversion crosses a midpoint when a left-half value is greater than a right-half value."},{"level":2,"content":"After both halves are sorted, one right pointer can count all smaller right-half values for each left value."},{"level":3,"content":"Merge the two sorted halves after counting so parent intervals can use the same monotone-pointer logic."}],"guidedFlow":{"version":2,"progressRevision":"count-inversions-2026-11-20-three-kinds-one-pointer","approachSelection":{"contract":"approach-selection-v1","question":"Which way of counting should the function use?","decisionPrompt":"A list can hold 100,000 values, so compare how the work grows with the length of the list.","approaches":[{"id":"nested-loops","name":"Compare every pair","summary":"Compare each value with every value after it.","decisionReason":"It makes n(n - 1)/2 comparisons, which is 4,999,950,000 for a list of 100,000 values.","complexity":{"time":"O(n^2)","space":"O(1)"},"tradeoffs":["O(n^2) time and O(1) extra space."],"isOptimal":false},{"id":"merge-count","name":"Count while merge sorting","summary":"Count inside each half, count across the cut with one forward pointer over the sorted halves, then merge.","decisionReason":"Halving n values down to single values takes about log n rounds, and each round walks and merges the n values once, so 100,000 values take a few million steps.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["O(n log n) time and O(n) extra space for the merge."],"isOptimal":true}]},"codingCheckpoints":[{"id":"recursive-calls","title":"Count inside each half","description":"Write a helper that takes a range of the list. A range of one value returns 0. Any longer range is cut at its midpoint, and its count starts as the sum of what the helper returns for the two halves.","commonMistakes":["Returning 1 for a range of one value, which has no pair to count","Keeping only one half's result, so the inversions inside the other half are lost"],"hint":"The helper calls itself twice, once for the left half and once for the right half, and both results go into the count.","semanticSpec":{"intent":"Create a merge-sort helper that stops on collapsed intervals, splits by midpoint, and combines left and right recursive counts.","doneWhen":"The helper checks `lo >= hi`, computes `mid`, and combines recursive counts from both midpoint-separated intervals.","shouldFailWhen":"This step should fail if only one half recurses or if the midpoint interval split is missing.","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."],"proofSnippets":[{"id":"py-count-inversions-recursive-calls","language":"python","code":"class Solution:\n    def countInversions(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"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sequence-ordering","fact":"recurses_on_midpoint_split_intervals","scope":"recursive-calls","readMode":"sequence-ordering-value-query-v1"}]}},{"id":"count-cross-pairs","title":"Count the inversions that cross the cut","description":"Both halves are sorted by now. Walk the left half in order and keep one pointer on the right half. Move the pointer forward while the left value is larger than the value under it, then add the number of right values the pointer has passed.","commonMistakes":["Moving the pointer on equal values, which counts pairs that are not inversions","Overwriting the count from the two halves with the crossing count","Reading past the end of the right half when every right value is smaller"],"hint":"The pointer is set to the first right value once, before the walk, and never moved back. What a left value adds is the pointer's distance from that starting index.","semanticSpec":{"intent":"Count cross-half inversions before merging the two sorted halves.","doneWhen":"The code advances a right-half pointer while `nums[i] > nums[j]` and adds the advanced width to the interval count.","shouldFailWhen":"This step should fail if the cross-pair contribution is never added.","roles":["left scan","right boundary pointer","strict comparison","cross-pair count"],"mustProve":["The code scans left-half positions after recursive sorting.","The code adds the number of smaller right-half values to the count."],"mustNotAccept":["Counting with a non-strict comparison.","Replacing the count instead of adding cross pairs to it."],"equivalentVariants":["Use a single right pointer that only moves forward across the sorted right half."],"proofSnippets":[{"id":"py-count-inversions-count-cross","language":"python","code":"class Solution:\n    def countInversions(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] > nums[j]:\n                    j += 1\n                count += j - (mid + 1)\n        return 0"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"additively_updates_accumulator","scope":"update-total","readMode":"array-scan-value-query-v1"}]}},{"id":"merge-arrays","title":"Merge the two halves back into the list","description":"Merge the two sorted halves into a temporary list: take the smaller front value each time, then whatever one half has left over. Write the result back over the same range.","commonMistakes":["Merging before the crossing count is taken, when the two halves can no longer be told apart","Building the merged list and never writing it back","Stopping when one half runs out and dropping the rest of the other"],"hint":"The range above counts across its own cut with this range as one of its halves, so it has to find these values in sorted order in the list itself.","semanticSpec":{"intent":"Restore sorted order for the current interval so parent calls can count correctly.","doneWhen":"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.","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]`."],"proofSnippets":[{"id":"py-count-inversions-merge-arrays","language":"python","code":"class Solution:\n    def countInversions(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] > 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"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sequence-ordering","fact":"merges_sorted_intervals_with_writeback","scope":"merge-arrays","readMode":"sequence-ordering-value-query-v1"}]}},{"id":"return-total","title":"Return the count","description":"The helper returns its count for the range, and the function returns the helper's result for the range that covers the whole list.","commonMistakes":["Returning the sorted list","Returning only the crossing count of the last range"],"hint":"The sorted list is a by-product. The answer is the number the helper returns for the range from the first index to the last.","semanticSpec":{"intent":"Return the count accumulated from left-half, right-half, and cross-half inversions.","doneWhen":"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 merge buffer, or an unrelated scalar.","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."],"proofSnippets":[{"id":"py-count-inversions-return-total","language":"python","code":"class Solution:\n    def countInversions(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] > 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)"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_terminal_accumulator","scope":"return-result","readMode":"array-scan-value-query-v1"}]}}],"slides":[{"id":"read-the-problem","kind":"info","title":"Count the pairs that are in the wrong order","workspacePanel":"problem","body":["You are given a list of numbers. Two of them form an inversion when the larger one comes earlier in the list and the smaller one comes later.","Return how many inversions the list has."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"an-inversion","title":"4 comes before 1 and is larger","summary":"That pair is an inversion.","state":{"nums":[2,4,1,3,5],"i":1,"j":2,"labels":{"i":"earlier","j":"later"}}},{"id":"a-pair-in-order","title":"4 comes before 5 and is smaller","summary":"That pair is in order, so it does not count.","state":{"nums":[2,4,1,3,5],"i":1,"j":4,"labels":{"i":"earlier","j":"later"}}}]}},{"id":"count-by-hand","kind":"case-probe","title":"How many inversions does this list have?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"the-list","state":{"nums":[2,4,1,3,5]}}]},"options":[{"id":"one-neighbor-pair","label":"1: the pair 4 and 1","rationale":"2 comes before 1 and is larger, and 4 comes before 3 and is larger. The two values of an inversion do not have to be neighbors.","isCorrect":false},{"id":"two-pairs","label":"2: the pairs 4 and 1, 4 and 3","rationale":"2 comes before 1 and is larger, so that pair counts as well. The 4 sitting between them changes nothing.","isCorrect":false},{"id":"three-pairs","label":"3: the pairs 2 and 1, 4 and 1, 4 and 3","rationale":"In each of those pairs the larger value comes first. In the other 7 pairs the smaller value comes first.","isCorrect":true},{"id":"four-pairs","label":"4: the pairs 2 and 1, 4 and 1, 4 and 3, 4 and 2","rationale":"4 is larger than 2, but 2 is the one that comes first, so that pair is in order.","isCorrect":false}]},{"id":"brute-force","kind":"code-trace","title":"The direct way compares every pair","workspacePanel":"trace","body":["Each value is compared with every value after it, and `count` goes up by 1 whenever the later value is smaller."],"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] > nums[j]:\n            count += 1\nreturn count","steps":[{"id":"scan-from-2","title":"2 against 4, 1, 3 and 5","codeLine":4,"summary":"4 comparisons find one smaller value, the 1.","state":{"nums":[2,4,1,3,5],"i":0,"j":4,"count":1,"comparisons":4}},{"id":"scan-from-4","title":"4 against 1, 3 and 5","codeLine":4,"summary":"3 comparisons find two smaller values, 1 and 3.","state":{"nums":[2,4,1,3,5],"i":1,"j":4,"count":3,"comparisons":7}},{"id":"scan-from-1","title":"1 against 3 and 5","codeLine":4,"summary":"2 comparisons find nothing smaller.","state":{"nums":[2,4,1,3,5],"i":2,"j":4,"count":3,"comparisons":9}},{"id":"scan-from-3","title":"3 against 5","codeLine":4,"summary":"1 comparison finds nothing smaller.","state":{"nums":[2,4,1,3,5],"i":3,"j":4,"count":3,"comparisons":10}},{"id":"brute-return","title":"The loops return 3","codeLine":6,"summary":"That took 4 + 3 + 2 + 1 = 10 comparisons, one for every pair in a list of 5.","state":{"nums":[2,4,1,3,5],"count":3,"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] > 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] > 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) > 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] > 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] > 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":"The same loops run on a list of 100,000 values. About how many comparisons do they make?","workspacePanel":"trace","options":[{"id":"one-per-value","label":"About 100,000: one for each value","rationale":"Each value is compared with every value after it. The first value alone takes 99,999 comparisons.","isCorrect":false},{"id":"two-loops-add","label":"About 200,000: 100,000 for each of the two loops","rationale":"The inner loop starts over for every value the outer loop reaches, so the two loops multiply.","isCorrect":false},{"id":"one-per-pair","label":"About 5 billion: one for each pair of values","rationale":"Adding 99,999 for the first value, 99,998 for the second, and so on down to 1 gives 4,999,950,000. A list can be this long, so the count has to come from far fewer comparisons than one per pair.","isCorrect":true}]},{"id":"split-in-two","kind":"case-probe","title":"Cut the list in two. Which inversion has one value in each half?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-halves","state":{"arrays":[{"name":"left half","values":[2,4,1]},{"name":"right half","values":[3,5]}]}}]},"options":[{"id":"two-one","label":"2 before 1","rationale":"2 and 1 are both in the left half.","isCorrect":false},{"id":"four-one","label":"4 before 1","rationale":"4 and 1 are both in the left half.","isCorrect":false},{"id":"four-three","label":"4 before 3","rationale":"4 is in the left half and 3 is in the right half. Every inversion has both values in the left half, both in the right half, or one in each. Here those counts are 2, 0 and 1, which make the 3.","isCorrect":true}]},{"id":"sorting-a-half","kind":"case-probe","title":"Which count changes when the left half is sorted?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"left-half-sorted","state":{"arrays":[{"name":"left half","values":[2,4,1]},{"name":"left half, sorted","values":[1,2,4]},{"name":"right half","values":[3,5]}]}}]},"options":[{"id":"inside-left","label":"The inversions inside the left half: 2 become 0","rationale":"2 before 1 and 4 before 1 are gone once 1 moves to the front. 4 before 3 is still there, because every left value is still ahead of every right value. So once a half's own inversions are counted, sorting it leaves the count across the cut unchanged.","isCorrect":true},{"id":"crossing","label":"The inversions that cross the cut: 1 becomes 0","rationale":"4 is still in the left half and 3 is still in the right half, so 4 still comes before 3.","isCorrect":false},{"id":"both","label":"Both counts change","rationale":"Sorting only moves values around inside the left half. Every left value stays ahead of every right value, so the crossing inversions are untouched.","isCorrect":false}]},{"id":"sorted-halves-leverage","kind":"case-probe","title":"Both halves are now sorted. Counting across the cut, 1 is compared with 3 and is not larger. What else does 1 need to be compared with?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"sorted-halves","state":{"arrays":[{"name":"left half, sorted","values":[1,2,4],"current":0},{"name":"right half, sorted","values":[3,5],"current":0}]}}]},"options":[{"id":"nothing-more","label":"Nothing else: 5 cannot be smaller than 1","rationale":"The right half is sorted, so 5 is at least as large as 3, and 3 is already larger than 1. One comparison has ruled out the whole right half.","isCorrect":true},{"id":"the-other-right-value","label":"5, the other value in the right half","rationale":"5 comes after 3 in a sorted half, so it is at least as large as 3. It cannot be smaller than 1.","isCorrect":false},{"id":"rest-of-left-half","label":"2 and 4, the rest of the left half","rationale":"2 and 4 are in the same half as 1. An inversion across the cut pairs 1 with a value from the right half.","isCorrect":false}]},{"id":"dry-run-setup","kind":"info","title":"Each half is cut the same way, inside the same list","workspacePanel":"visualizer","body":["So the work goes in this order: count inside each half, sort both halves, then count across the cut. Each half is the same problem on a shorter list, so it is cut the same way, down to single values.","A half is a range of the list, from a first index `lo` to a last index `hi`. Nothing is copied out. A range cannot finish its count until both of its halves have returned theirs.","While a range counts across its cut, `i` marks the left value being counted and `j` marks the right value it is compared with next."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"whole-range","title":"The whole list is the range 0 to 4","summary":"Its cut is at `mid` = (0 + 4) / 2 = 2. The left half ends at index 2, and the right half starts at index 3.","state":{"nums":[2,4,1,3,5],"left":0,"right":4,"mid":2,"labels":{"left":"lo","right":"hi"}}},{"id":"left-range","title":"Its left half is the range 0 to 2","summary":"The same cut, at `mid` = 1, splits it into [2, 4] and [1].","state":{"nums":[2,4,1,3,5],"left":0,"right":2,"mid":1,"labels":{"left":"lo","right":"hi"}}},{"id":"pair-range","title":"That range's left half is 0 to 1","summary":"(0 + 1) / 2 rounds down to `mid` = 0, so each half is a single value.","state":{"nums":[2,4,1,3,5],"left":0,"right":1,"mid":0,"labels":{"left":"lo","right":"hi"}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Count the range 0 to 2","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pair-setup","state":{"nums":[2,4,1,3,5],"left":0,"right":1,"mid":0,"labels":{"left":"lo","right":"hi"}}},{"id":"sweep-at-2","state":{"nums":[2,4,1,3,5],"left":0,"right":2,"mid":1,"i":0,"j":2,"count":0,"labels":{"left":"","right":""}}},{"id":"sweep-at-4","state":{"nums":[2,4,1,3,5],"left":0,"right":2,"mid":1,"i":1,"j":3,"count":1,"labels":{"left":"","right":""}}},{"id":"range-counted","state":{"nums":[2,4,1,3,5],"left":0,"right":2,"mid":1,"i":1,"j":3,"count":2,"labels":{"left":"","right":""}}}]},"beats":[{"id":"pair-returns","title":"The range 0 to 1 has a single value in each half. What does it return?","summary":"","prompt":"","options":[{"id":"zero-in-order","label":"0: no pair in it is out of order","rationale":"Each half returns 0, because one value cannot form a pair. The only pair that crosses the cut is 2 before 4, and its smaller value comes first.","isCorrect":true},{"id":"one-comparison","label":"1: one pair was compared","rationale":"A range returns the number of inversions it found. 2 and 4 were compared, and they are in order.","isCorrect":false},{"id":"two-values","label":"2: one for each value in it","rationale":"Inversions are pairs of values. A single value forms none, so a range of one value returns 0.","isCorrect":false}]},{"id":"two-meets-one","title":"The range 2 to 2 holds only the 1 and returns 0. Back in the range 0 to 2, 2 is compared with 1. What happens to `j` and to the count?","summary":"","prompt":"","options":[{"id":"j-passes-one","label":"The pointer moves past 1, and the count goes up by 1","rationale":"2 is larger than 1, an inversion across the cut, so the pointer moves past the 1 and uses up the right half. A left value adds the number of right values the pointer has passed. The right half starts at index 2, which is `mid + 1`, and the pointer is now at index 3, so 2 adds 3 - 2 = 1.","isCorrect":true},{"id":"j-stays","label":"The pointer stays on 1, and the count stays at 0","rationale":"The pointer stops at a right value that is not smaller than the left value, or at the end of the right half. 2 is larger than 1 and comes first, so the pair is an inversion.","isCorrect":false},{"id":"j-passes-uncounted","label":"The pointer moves past 1, and the count stays at 0","rationale":"The pointer only passes a right value that is smaller than the left value, and every such pair is an inversion to count.","isCorrect":false}]},{"id":"four-inherits","title":"4 is the next left value, and `j` is already past the whole right half. What does 4 add?","summary":"","prompt":"","options":[{"id":"adds-zero","label":"0: there is no right value left to compare 4 with","rationale":"4 needs no comparison to be counted against the 1. It is at least as large as 2, and 2 was already larger than 1.","isCorrect":false},{"id":"adds-one","label":"1: the value `j` passed is smaller than 4 as well","rationale":"The left half is sorted, so 4 is at least as large as 2, and 2 was larger than 1. Whatever an earlier left value passed, a later one passes too, so `j` never moves back. 4 adds `j - (mid + 1)` = 3 - 2 = 1 with no comparison at all.","isCorrect":true},{"id":"adds-two","label":"2: 4 is larger than both 2 and 1","rationale":"2 is in the same half as 4, and it comes first and is smaller. Only values in the right half are counted here.","isCorrect":false}]}]},{"id":"merge-back","kind":"info","title":"Before it returns, the range is put in sorted order","workspacePanel":"visualizer","body":["The count for the range 0 to 2 is 0 + 0 + 2 = 2. Its two halves, [2, 4] and [1], are each sorted already, so putting the range in order only takes a merge."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"fronts","title":"The front values are 2 and 1","summary":"The smaller one is copied into a temporary list, `temp`.","state":{"arrays":[{"name":"nums","values":[2,4,1,3,5],"left":0,"right":2,"i":0,"j":2,"labels":{"left":"","right":"","i":"left front","j":"right front"}},{"name":"temp","values":[]}]}},{"id":"right-used-up","title":"1 is copied, and the right half is used up","summary":"Nothing is left to compare the 2 against.","state":{"arrays":[{"name":"nums","values":[2,4,1,3,5],"left":0,"right":2,"i":0,"labels":{"left":"","right":"","i":"left front","j":"right front"}},{"name":"temp","values":[1]}]}},{"id":"rest-of-left","title":"The rest of the left half follows as it stands","summary":"2 and then 4 are copied over in the order they already have.","state":{"arrays":[{"name":"nums","values":[2,4,1,3,5],"left":0,"right":2,"labels":{"left":"","right":"","i":"left front","j":"right front"}},{"name":"temp","values":[1,2,4]}]}},{"id":"written-back","title":"`temp` is written back over the range","summary":"The range 0 to 2 now reads 1, 2, 4. The values outside it have not moved.","state":{"arrays":[{"name":"nums","values":[1,2,4,3,5],"left":0,"right":2,"labels":{"left":"","right":"","i":"left front","j":"right front"}},{"name":"temp","values":[1,2,4]}]}}]}},{"id":"whole-list","kind":"dry-run","source":"trace-example","title":"Count the whole list","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"whole-setup","state":{"nums":[1,2,4,3,5],"left":0,"right":4,"mid":2,"i":0,"j":3,"count":2,"labels":{"left":"","right":""}}},{"id":"whole-at-4","state":{"nums":[1,2,4,3,5],"left":0,"right":4,"mid":2,"i":2,"j":3,"count":2,"labels":{"left":"","right":""}}},{"id":"whole-counted","state":{"nums":[1,2,4,3,5],"left":0,"right":4,"mid":2,"i":2,"j":4,"count":3,"labels":{"left":"","right":""}}}]},"beats":[{"id":"one-and-two","title":"1 and then 2 are each compared with 3. What do they add to the count?","summary":"","prompt":"The left half returned 2 and the right half, [3, 5], returned 0.","options":[{"id":"add-nothing","label":"Nothing: neither is larger than 3, and `j` stays on 3","rationale":"1 is not larger than 3, so the pointer does not move and 1 adds 0. 2 finds it still on 3 and adds 0 as well. 5 is never looked at.","isCorrect":true},{"id":"still-need-five","label":"Nothing yet: each still has to be compared with 5","rationale":"5 comes after 3 in a sorted half, so it is at least as large as 3. A left value that is not larger than 3 cannot be larger than 5.","isCorrect":false},{"id":"one-each","label":"1 each: both come before 3","rationale":"Coming first is only half of an inversion. The earlier value also has to be the larger one, and 1 and 2 are both smaller than 3.","isCorrect":false}]},{"id":"four-passes-three","title":"4 is the next left value, and it is larger than 3. How far does `j` go, and what does 4 add?","summary":"","prompt":"","options":[{"id":"stops-at-five","label":"To 5, where it stops: 4 adds 1","rationale":"4 is larger than 3 and smaller than 5, so the pointer passes 3 and stops on 5, and 4 adds 1. The whole list returns 2 + 0 + 1 = 3. Counting across this cut took 4 comparisons for its 6 pairs.","isCorrect":true},{"id":"passes-five","label":"Past 5 as well: 4 adds 2","rationale":"The pointer moves only while the left value is larger than the value under it. 4 is smaller than 5.","isCorrect":false},{"id":"stays-on-three","label":"Nowhere, it stays on 3: 4 adds 0","rationale":"4 is larger than 3, so 4 before 3 is an inversion. The pointer has to move past 3 for it to be counted.","isCorrect":false}]}]},{"id":"edge-case-intro","kind":"info","title":"The whole list gives 3. Next, two runs that each change one thing.","workspacePanel":"visualizer","body":["The first run uses the same list but skips every merge. The second uses [2, 2, 1], a list with two equal values."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"the-list-again","state":{"nums":[2,4,1,3,5]}}]}},{"id":"skip-merge-pitfall","kind":"case-probe","title":"In the first run nothing is merged, so the left half is still [2, 4, 1]. 4 has pushed `j` past 3, and `j` never moves back. What does 1 add to the count?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"unmerged-sweep","state":{"nums":[2,4,1,3,5],"left":0,"right":4,"mid":2,"i":2,"j":4,"count":3,"labels":{"left":"","right":""}}}]},"options":[{"id":"credited-with-three","label":"1: it is credited with the 3 that `j` already passed","rationale":"1 is not larger than 5, so `j` stays one index past the start of the right half, and 1 adds 1. But 1 is smaller than 3, so that pair is no inversion, and the list returns 4 where the answer is 3. Carrying `j` forward only works when each left value is at least as large as the one before it, and the merge is what leaves each half in that order.","isCorrect":true},{"id":"true-zero","label":"0: 1 is smaller than both 3 and 5","rationale":"That is the true number of right values smaller than 1. But 1 is never compared with 3: what it adds is read off how far the pointer has moved.","isCorrect":false},{"id":"j-moves-back","label":"2: it is credited with both 3 and 5","rationale":"The pointer moves only while the left value is larger than the value under it. 1 is not larger than 5, so the pointer stays on 5 and has passed the 3 alone.","isCorrect":false}]},{"id":"duplicates-probe","kind":"case-probe","title":"In [2, 2, 1], the range 0 to 1 compares 2 with an equal 2. Does `j` move?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"equal-values","state":{"nums":[2,2,1],"left":0,"right":1,"mid":0,"i":0,"j":1,"count":0,"labels":{"left":"","right":""}}}]},"options":[{"id":"stays-on-equal","label":"No: an inversion needs the earlier value to be larger","rationale":"The pointer moves only past right values that are smaller than the left value. Equal is not smaller, so it stays and this pair adds 0.","isCorrect":true},{"id":"moves-on-equal","label":"Yes: two equal values are not in increasing order","rationale":"Equal values are not out of order either. Moving the pointer here would count 2 before 2 as an inversion.","isCorrect":false},{"id":"needs-tie-rule","label":"It depends on a separate rule for ties","rationale":"The one comparison already covers ties. The pointer moves while the left value is larger, and an equal value is not larger.","isCorrect":false}]},{"id":"ready-to-code","kind":"info","title":"You have followed every step on [2, 4, 1, 3, 5]. Now write it for any list.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["The function counts a range of the list, starting with the whole list. A range of one value returns 0.","A longer range is cut at its middle index, and each half is counted the same way. Both halves come back sorted.","Then the range goes through its left values in order, with one pointer on the right half that only moves forward. Each left value adds the number of right values the pointer has passed.","Last, the range merges its halves into a temporary list and writes it back over the range. It returns its two halves' counts plus the count across its cut."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"the-list-to-code","state":{"nums":[2,4,1,3,5]}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Count the inversions","workspacePanel":"code"},{"id":"complete","kind":"complete","title":"Counting inversions on the way to a sorted list","workspacePanel":"code","takeaways":[{"title":"Three places an inversion can be","body":"Inside the left half, inside the right half, or across the cut. A range returns the sum of those three counts, and a range of one value returns 0."},{"title":"One pointer that only moves forward","body":"On sorted halves, a right value smaller than one left value is smaller than every later left value too. Each left value adds the number of right values already passed."},{"title":"Count, then merge","body":"Counting across the cut needs the two halves sorted and still separate, so a range counts first and merges second. The merge then leaves the range sorted for the range above it."},{"title":"O(n log n) time, O(n) extra space","body":"Halving a list of n values down to single values takes about log n rounds. The ranges in one round hold at most n values between them, so that round's walks and merges take O(n) time. Comparing every pair takes n(n - 1)/2 comparisons. The temporary list used by the merge is the extra space."}]}],"slidesOrigin":"authored"}}
