{"id":"count-increasing-pairs","title":"Count Increasing Pairs","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":0,"max":1000}},"description":"Given an integer array `nums`, return the number of index pairs `(i, j)` where `i < j` and `nums[i] < nums[j]`.\n\nUse 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":["countIncreasingPairs"],"case":"worst","enforcement":"hard","reason":"Each merge-sort level counts cross-half increasing pairs and merges the interval in linear time."}],"examples":[{"input":"nums = [1,3,2,4]","output":"5","explanation":"The increasing pairs are (1,3), (1,2), (1,4), (3,4), and (2,4)."},{"input":"nums = [4,3,2,1]","output":"0","explanation":"No earlier value is smaller than a later value."}],"constraints":[{"id":"0-len-nums-10-5","text":"0 <= len(nums) <= 10^5","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":0,"max":100000}},{"id":"0-nums-i-10-5","text":"0 <= nums[i] <= 10^5","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":0,"max":100000}},{"id":"the-answer-is-guaranteed-to-fit-in-a-64-bit-signed-integer","text":"The answer is guaranteed to fit in a 64-bit signed integer","check":{"kind":"guarantee","guarantee":"resultRange","width":"int64"}}],"starterCode":"class Solution:\n    def countIncreasingPairs(self, nums: list[int]) -> int:\n        # Your code here\n        pass","functionName":"countIncreasingPairs","testCases":[{"id":"1","input":{"nums":[1,3,2,4]},"expected":5,"description":"Mixed order with several increasing pairs."},{"id":"2","input":{"nums":[4,3,2,1]},"expected":0,"description":"Descending values produce no increasing pairs."},{"id":"3","input":{"nums":[1,1,2]},"expected":2,"description":"Equal values are not strictly increasing, but both ones pair with the final two."},{"id":"4","input":{"nums":[]},"expected":0,"description":"An empty array has no pairs."},{"id":"5","input":{"nums":[1,2,3,4]},"expected":6,"description":"Every pair in a strictly increasing array qualifies."},{"id":"6","input":{"nums":[3,1,4,2,5]},"expected":7,"description":"Pairs are counted across multiple merge levels."},{"id":"h1","input":{"nums":[5]},"expected":0,"description":"A single element has no increasing pairs."},{"id":"h2","input":{"nums":[2,2,2]},"expected":0,"description":"Equal values do not form strictly increasing pairs."},{"id":"h3","input":{"nums":[0,0,1,2]},"expected":5,"description":"Zeros at the front contribute to later larger values."},{"id":"h4","input":{"nums":[2,1,3,1,2]},"expected":4,"description":"Later increases are preserved across multiple positions."},{"id":"h5","input":{"nums":[2,0,2,1,3]},"expected":6,"description":"An empty array has no index pairs."},{"id":"h6","input":{"nums":[4,1,2,3]},"expected":3,"description":"A partially unsorted array still contributes increasing pairs across later larger values."}],"hints":[{"level":1,"content":"A pair is counted when the left value is in the left half and smaller than a value in the right half."},{"level":2,"content":"After both halves are sorted, one right pointer can skip values that are not greater than the current left value."},{"level":3,"content":"For each left value, every right-half value after the pointer is greater, so add that remaining width."}],"guidedFlow":{"version":2,"progressRevision":"count-increasing-pairs-2026-11-20-pairs-across-each-cut","approachSelection":{"contract":"approach-selection-v1","question":"Which way of counting should the function use?","decisionPrompt":"The list can hold 100,000 numbers.","approaches":[{"id":"nested-loops","name":"Check every pair","summary":"Compare each number with every number after it.","decisionReason":"One comparison settles one pair, and 100,000 numbers hold 4,999,950,000 pairs of positions.","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 across cuts while sorting","summary":"Cut the list in half, count inside each half the same way, count the pairs across the cut with a marker that only moves forward, then merge the halves.","decisionReason":"With both halves in order, the pairs across a cut are counted in a single trip through the right half, and 100,000 numbers need only 17 levels of cuts.","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":"Cut the piece and count inside each half","description":"Write a helper that takes the first and last positions of a piece. A piece with fewer than two numbers returns 0. Otherwise find the middle position, run the helper on each half, and add the two results.","commonMistakes":["Stopping only when the two positions are equal, which never stops on an empty list","Running the helper on one half only, so the pairs inside the other half are lost"],"hint":"An empty list arrives as a first position that is already past the last one.","semanticSpec":{"intent":"Create a merge-sort helper that stops on collapsed intervals, splits by midpoint, and combines left and right recursive totals.","doneWhen":"The helper checks `lo >= hi`, computes `mid`, and combines recursive results from both midpoint-separated intervals.","shouldFailWhen":"This step should fail if only one half recurses or if the midpoint split is missing.","roles":["lower bound","upper bound","midpoint","recursive total"],"mustProve":["The helper uses interval bounds and a midpoint split.","Both halves are processed recursively and their totals are combined."],"mustNotAccept":["Recursing on the original interval again.","Dropping either the left or right recursive total."],"equivalentVariants":["Use a nested merge-sort helper over inclusive interval bounds."],"proofSnippets":[{"id":"py-count-increasing-recursive-calls","language":"python","code":"class Solution:\n    def countIncreasingPairs(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            total = 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 pairs across the cut","description":"Both halves come back in order. For each number in the left half, move one marker through the right half past every number that is not larger. Then add how many right-half numbers remain from the marker to the end.","commonMistakes":["Stopping the marker on an equal number, which counts ties as pairs","Overwriting the total from the two halves with the across count instead of adding it"],"hint":"The marker starts at the front of the right half once and is never moved back for the next left number.","semanticSpec":{"intent":"Count cross-half increasing pairs before merging the two sorted halves.","doneWhen":"The code advances a right-half pointer past values `<= nums[i]` and adds the remaining right-half width.","shouldFailWhen":"This step should fail if the cross-pair contribution is never added.","roles":["left scan","right boundary pointer","strict smaller comparison","pair count contribution"],"mustProve":["The code scans left-half positions after recursive sorting.","The code adds a cross-half contribution to the running total."],"mustNotAccept":["Counting equal values as increasing pairs.","Replacing the total instead of adding cross-pair contributions to it."],"equivalentVariants":["Use one right pointer that only moves forward across the sorted right half."],"proofSnippets":[{"id":"py-count-increasing-cross-pairs","language":"python","code":"class Solution:\n    def countIncreasingPairs(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            total = 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[j] <= nums[i]:\n                    j += 1\n                total += hi - j + 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 halves back into the list","description":"Build the ordered piece by taking the smaller front number of the two halves, again and again. Copy over whatever is left on one side. Then write the result back over the positions of the piece in `nums`.","commonMistakes":["Merging before the across count, when the two halves can no longer be told apart","Dropping the numbers left over when one half runs out"],"hint":"The piece one level up reads its halves from the list itself, so a merged copy that stays in a separate buffer is never used.","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 contribution has been accumulated."],"equivalentVariants":["Use a temporary array and copy it back to `nums[lo:hi+1]`."],"proofSnippets":[{"id":"py-count-increasing-merge-arrays","language":"python","code":"class Solution:\n    def countIncreasingPairs(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            total = 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[j] <= nums[i]:\n                    j += 1\n                total += hi - j + 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 total","description":"The helper returns the pairs inside its left half, inside its right half and across its cut, added together. The function returns what the helper gives for the whole list.","commonMistakes":["Returning the ordered list instead of the count","Returning only the across count of the last cut"],"hint":"The pairs inside the halves reach the caller only if every piece passes them up.","semanticSpec":{"intent":"Return the total accumulated from left-half, right-half, and cross-half pair counts.","doneWhen":"Each helper call returns its accumulated total and the public method returns the total for the full interval.","shouldFailWhen":"This step should fail if the method returns the sorted array, merge buffer, or an unrelated scalar.","roles":["recursive subtotal","cross-half contribution","final return"],"mustProve":["The helper returns the accumulated total 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-pair contribution without recursive subtotals."],"equivalentVariants":["Return `total` from the helper and return the helper call over the full interval."],"proofSnippets":[{"id":"py-count-increasing-return-total","language":"python","code":"class Solution:\n    def countIncreasingPairs(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            total = 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[j] <= nums[i]:\n                    j += 1\n                total += hi - j + 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 total\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 go up","workspacePanel":"problem","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frame","state":{"nums":[3,1,4,2,5]}}]},"body":["You are given a list of numbers. Count the pairs where the earlier number is smaller than the later one. The two numbers do not have to sit next to each other.","In the list drawn here, 3 comes before 4 and is smaller, so that pair counts. 3 also comes before 1, and that pair does not. Seven pairs count in all, so the function returns 7."]},{"id":"brute-force","kind":"code-trace","title":"Check every pair","workspacePanel":"trace","body":["The direct way is to take each number in turn and compare it with every number after it. `i` marks the earlier number and `j` the later one."],"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":"three-scans","title":"3 is compared with all four numbers after it","codeLine":5,"summary":"Only 4 and 5 are bigger than 3, so `count` is 2 after four comparisons.","state":{"nums":[3,1,4,2,5],"i":0,"j":4,"count":2}},{"id":"one-restarts","title":"`j` starts over, one place after 1","codeLine":3,"summary":"Nothing found while scanning for 3 is reused. 1 gets its own trip over 4, 2 and 5.","state":{"nums":[3,1,4,2,5],"i":1,"j":2,"count":2}},{"id":"one-scans","title":"1 is smaller than all three","codeLine":5,"summary":"Three more comparisons add three pairs, and `count` reaches 5.","state":{"nums":[3,1,4,2,5],"i":1,"j":4,"count":5}},{"id":"four-scans","title":"4 is compared with 2 and 5","codeLine":5,"summary":"Only 5 is bigger than 4, so two comparisons add one pair and `count` is 6.","state":{"nums":[3,1,4,2,5],"i":2,"j":4,"count":6}},{"id":"two-scans","title":"2 is compared with 5","codeLine":5,"summary":"One comparison adds the last pair, and `count` is 7.","state":{"nums":[3,1,4,2,5],"i":3,"j":4,"count":7}},{"id":"return-count","title":"7 pairs, found with 10 comparisons","codeLine":6,"summary":"5 is last and has nothing after it. The 10 comparisons are 4 + 3 + 2 + 1, one for every pair of positions in the list.","state":{"nums":[3,1,4,2,5],"i":4,"count":7}}],"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":"Five numbers took 10 comparisons. About how many would 100,000 numbers take?","workspacePanel":"trace","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frame","state":{"nums":[3,1,4,2,5],"comparisons":10}}]},"options":[{"id":"quadratic","label":"About 5 billion","rationale":"The first number is compared with 99,999 others, the next with 99,998, and so on down to 1. That adds up to 4,999,950,000. Each comparison settles only one pair, so a faster count needs comparisons that settle many pairs at once.","isCorrect":true},{"id":"linear","label":"About 200,000","rationale":"Two comparisons per number fits 5 numbers and 10 comparisons, but in a list of 100,000 the first number alone needs 99,999.","isCorrect":false},{"id":"one-each","label":"About 100,000","rationale":"One comparison per number would mean each number meets a single partner. Each number is compared with every number after it.","isCorrect":false}]},{"id":"split-in-half","kind":"info","title":"Cut the list in two","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frame","state":{"arrays":[{"name":"left half","values":[3,1,4]},{"name":"right half","values":[2,5]}]}}]},"body":["Cut the list after its middle number. The left half is [3, 1, 4] and the right half is [2, 5].","Counted on its own, the left half holds 2 pairs: 3 with 4, and 1 with 4. The right half holds 1 pair: 2 with 5."]},{"id":"three-kinds","kind":"case-probe","title":"The whole list holds 7 pairs and the two halves account for 3. Where are the other 4?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frame","state":{"arrays":[{"name":"left half","values":[3,1,4]},{"name":"right half","values":[2,5]}],"whole list":7,"inside left half":2,"inside right half":1}}]},"options":[{"id":"across","label":"They have one number in each half","rationale":"They are 3 with 5, 1 with 2, 1 with 5 and 4 with 5. Counting inside a half never compares a left number with a right number, so these four are left over.","isCorrect":true},{"id":"missed","label":"They are inside the left half and were missed","rationale":"The left half is [3, 1, 4]. 3 with 4 and 1 with 4 count and 3 with 1 does not, so 2 is its full count.","isCorrect":false},{"id":"double","label":"They are pairs the halves counted twice","rationale":"The halves counted 3 with 4, 1 with 4 and 2 with 5, three different pairs. None of the missing 4 was counted at all.","isCorrect":false}]},{"id":"split-until-one","kind":"info","title":"Each half is cut again, down to single numbers","workspacePanel":"visualizer","body":["So a list's count is the pairs inside its left half, plus the pairs inside its right half, plus the pairs across the cut. Each half is a shorter list, so it gets the same cut."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"whole","title":"A piece is named by its two end positions","summary":"The whole list is the piece from position 0 to position 4. Call the ends `lo` and `hi`.","state":{"nums":[3,1,4,2,5],"left":0,"right":4,"labels":{"left":"lo","right":"hi"}}},{"id":"middle","title":"The cut goes after the middle position","summary":"`mid` is (lo + hi) / 2 rounded down, which is 2 here. The left half runs from `lo` to `mid`, and the right half from `mid + 1` to `hi`.","state":{"nums":[3,1,4,2,5],"left":0,"right":4,"mid":2,"labels":{"left":"lo","right":"hi"}}},{"id":"left-piece","title":"The left half is cut the same way","summary":"For the piece from 0 to 2, `mid` is 1. Its halves are [3, 1] and [4].","state":{"nums":[3,1,4,2,5],"left":0,"right":2,"mid":1,"labels":{"left":"lo","right":"hi"}}},{"id":"pair-piece","title":"[3, 1] is cut into 3 and 1","summary":"For the piece from 0 to 1, `mid` is (0 + 1) / 2 rounded down, which is 0.","state":{"nums":[3,1,4,2,5],"left":0,"right":1,"mid":0,"labels":{"left":"lo","right":"hi"}}},{"id":"single","title":"A single number is not cut","summary":"A piece with one number holds no pairs, so it returns 0 right away.","state":{"nums":[3,1,4,2,5],"left":0,"right":0,"labels":{"left":"lo","right":"hi"}}},{"id":"right-piece","title":"The right half goes through the same cuts","summary":"[2, 5] is the piece from 3 to 4. It is cut into 2 and 5, and each of those returns 0.","state":{"nums":[3,1,4,2,5],"left":3,"right":4,"mid":3,"labels":{"left":"lo","right":"hi"}}}]}},{"id":"order-inside-a-half","kind":"case-probe","title":"Suppose the left half is rearranged from [3, 1, 4] into [1, 3, 4]. How many pairs cross the cut now?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frame","state":{"arrays":[{"name":"left half","values":[1,3,4]},{"name":"right half","values":[2,5]}]}}]},"options":[{"id":"still-four","label":"Still 4","rationale":"Every left number is still earlier than every right number, so whether a pair across the cut counts depends only on its two values. Once a half's own pairs are counted, the half can be rearranged without changing the count across the cut.","isCorrect":true},{"id":"one-more","label":"5, because moving 1 to the front adds a pair","rationale":"It does add one, 1 before 3, but both of those numbers are in the left half. No pair across the cut is new.","isCorrect":false},{"id":"unknown","label":"It cannot be known without recounting","rationale":"Recounting gives 4 again, and it has to. The rearranging stayed inside the left half, and a pair across the cut does not depend on where in its half a number sits.","isCorrect":false}]},{"id":"cross-count-discovery","kind":"case-probe","title":"This time each half is put in order after its own pairs are counted. 1 is smaller than 2. What does that say about 1 and 5?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frame","state":{"arrays":[{"name":"left half","values":[1,3,4],"i":0},{"name":"right half","values":[2,5],"j":0}]}}]},"options":[{"id":"free","label":"1 is smaller than 5 too, and no comparison is needed","rationale":"The right half is in order, so 5 is at least as big as 2, and 2 is already bigger than 1. One comparison settled more than one pair. With 50,000 ordered numbers in the right half, one comparison could settle 50,000.","isCorrect":true},{"id":"must-compare","label":"Nothing, because 1 and 5 have not been compared","rationale":"The comparison could only come out one way. A number that comes after 2 in an ordered half cannot be smaller than 2.","isCorrect":false},{"id":"rearranged","label":"5 might be smaller than 1, since the left half was rearranged","rationale":"Rearranging the left half moved no number across the cut and changed no value. 5 is at least as big as 2, and 2 is bigger than 1.","isCorrect":false}]},{"id":"dry-run-setup","kind":"info","title":"The pieces finish from the smallest up","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frame","state":{"nums":[3,1,4,2,5],"left":0,"right":1,"mid":0,"labels":{"left":"lo","right":"hi"}}}]},"body":["A piece can count across its cut only after both of its halves have returned, so the single numbers return first and the whole list goes last.","While a piece counts across its cut, `i` marks the left number being counted and `j` marks a number in the right half, starting at its front."]},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Follow [3, 1, 4, 2, 5] from the smallest piece to the whole list","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup","state":{"arrays":[{"name":"left half","values":[3]},{"name":"right half","values":[1]}]}},{"id":"piece-3-1","state":{"arrays":[{"name":"left half","values":[1,3]},{"name":"right half","values":[4]}],"left half returned":0,"right half returned":0}},{"id":"piece-13-4","state":{"arrays":[{"name":"left half","values":[1,3,4],"i":0},{"name":"right half","values":[2,5],"j":0}],"left half returned":2,"right half returned":1,"across":0}},{"id":"sweep-one","state":{"arrays":[{"name":"left half","values":[1,3,4],"i":1},{"name":"right half","values":[2,5],"j":0}],"left half returned":2,"right half returned":1,"across":2}},{"id":"sweep-three","state":{"arrays":[{"name":"left half","values":[1,3,4],"i":2},{"name":"right half","values":[2,5],"j":1,"used":[0]}],"left half returned":2,"right half returned":1,"across":3}},{"id":"sweep-four","state":{"arrays":[{"name":"left half","values":[1,3,4],"i":2},{"name":"right half","values":[2,5],"j":1,"used":[0]}],"left half returned":2,"right half returned":1,"across":4}}]},"beats":[{"id":"piece-3-1","title":"The first piece with two numbers is [3, 1]. What does it return, and how does it leave the two numbers?","options":[{"id":"zero-ordered","label":"It returns 0 and leaves [1, 3]","rationale":"3 is not smaller than 1, so no pair crosses this cut. The piece is put in order all the same, since it is about to be part of a left half.","isCorrect":true},{"id":"zero-unordered","label":"It returns 0 and leaves [3, 1]","rationale":"0 is the right count. Left as [3, 1], though, these two numbers could not be part of an ordered half one level up.","isCorrect":false},{"id":"one-ordered","label":"It returns 1 and leaves [1, 3]","rationale":"1 before 3 exists only after the reordering. In the list 3 comes first, and the count is taken before the piece is put in order.","isCorrect":false}]},{"id":"piece-13-4","title":"This piece is [1, 3] with [4], and both halves returned 0. What does it return?","options":[{"id":"two","label":"2","rationale":"1 with 4 and 3 with 4 cross the cut, and 0 + 0 + 2 = 2.","isCorrect":true},{"id":"three","label":"3","rationale":"That counts 1 with 3 as well. That pair was settled inside the left half while it was still [3, 1], and it did not count. A piece adds only the pairs across its own cut.","isCorrect":false},{"id":"zero","label":"0","rationale":"The halves returned 0 for their own insides. The pairs across this cut are still uncounted.","isCorrect":false}]},{"id":"sweep-one","title":"[2, 5] returns 1 the same way, and the last piece is the whole list. `i` is on 1 and `j` is on 2. How many pairs does 1 add?","options":[{"id":"both","label":"2","rationale":"2 is bigger than 1, and 5 comes after 2 in an ordered half, so both count. `j` did not have to move.","isCorrect":true},{"id":"one","label":"1","rationale":"That counts only the number `j` is on. Every right number after `j` is at least as big, so 5 counts too.","isCorrect":false},{"id":"none","label":"0","rationale":"`j` already rests on a number bigger than 1. Everything from `j` to the end of the right half is a pair for 1.","isCorrect":false}]},{"id":"sweep-three","title":"`i` moves to 3, and 2 is not bigger than 3. What happens to `j`, and how many pairs does 3 add?","options":[{"id":"move-one","label":"`j` moves to 5, and 3 adds 1","rationale":"`j` steps past every right number that is not bigger than 3 and stops at the first one that is. From 5 to the end is one number.","isCorrect":true},{"id":"stay","label":"`j` stays on 2, and 3 adds 2","rationale":"That would count 3 with 2, and 3 is not smaller than 2.","isCorrect":false},{"id":"off-end","label":"`j` moves past 5, and 3 adds 0","rationale":"5 is bigger than 3, so `j` stops on it and 3 with 5 counts.","isCorrect":false}]},{"id":"sweep-four","title":"`i` moves to 4. Which right numbers does 4 still have to be compared with?","options":[{"id":"only-five","label":"Only 5, the number `j` is on","rationale":"2 was not bigger than 3, and 4 is at least as big as 3, so 2 cannot be bigger than 4. 5 is bigger than 4, so `j` stays and 4 adds 1.","isCorrect":true},{"id":"both-again","label":"2 and 5, starting again from the front","rationale":"Comparing 4 with 2 can only repeat what 3 already found. The left half is in order, so anything too small for 3 is too small for 4.","isCorrect":false},{"id":"none-needed","label":"None, because 4 adds the same 1 that 3 added","rationale":"4 does add 1, but only because 5 is bigger than 4. Had that right number been 4 or less, `j` would have moved on and 4 would have added 0.","isCorrect":false}]}]},{"id":"merge-halves","kind":"info","title":"The piece is put in order by merging its halves","workspacePanel":"visualizer","body":["The count across the cut is 2 + 1 + 1 = 4. It took four comparisons, where checking each left number against each right number takes six. With that count finished, the two halves no longer have to stay apart."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"fronts","title":"Compare the two front numbers","summary":"Each half is in order, so its smallest number is at its front. 1 is smaller than 2, which makes 1 the smallest number in the piece.","state":{"arrays":[{"name":"left half","values":[1,3,4],"i":0,"labels":{"i":"front"}},{"name":"right half","values":[2,5],"j":0,"labels":{"j":"front"}},{"name":"merged","values":[]}]}},{"id":"place-1","title":"1 is placed, and the fronts are now 3 and 2","summary":"2 is the smaller front, so it goes next.","state":{"arrays":[{"name":"left half","values":[1,3,4],"i":1,"used":[0],"labels":{"i":"front"}},{"name":"right half","values":[2,5],"j":0,"labels":{"j":"front"}},{"name":"merged","values":[1]}]}},{"id":"place-2","title":"The fronts are 3 and 5","summary":"3 is smaller, so it goes next.","state":{"arrays":[{"name":"left half","values":[1,3,4],"i":1,"used":[0],"labels":{"i":"front"}},{"name":"right half","values":[2,5],"j":1,"used":[0],"labels":{"j":"front"}},{"name":"merged","values":[1,2]}]}},{"id":"place-3","title":"The fronts are 4 and 5","summary":"4 is smaller, so it goes next.","state":{"arrays":[{"name":"left half","values":[1,3,4],"i":2,"used":[0,1],"labels":{"i":"front"}},{"name":"right half","values":[2,5],"j":1,"used":[0],"labels":{"j":"front"}},{"name":"merged","values":[1,2,3]}]}},{"id":"left-used-up","title":"The left half is used up","summary":"[1, 2, 3, 4] is placed, and only 5 remains in the right half.","state":{"arrays":[{"name":"left half","values":[1,3,4],"used":[0,1,2],"labels":{"i":"front"}},{"name":"right half","values":[2,5],"j":1,"used":[0],"labels":{"j":"front"}},{"name":"merged","values":[1,2,3,4]}]}}]}},{"id":"merge-leftover","kind":"case-probe","title":"The left half is used up and 5 is still in the right half. What happens to 5?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frame","state":{"arrays":[{"name":"left half","values":[1,3,4],"used":[0,1,2],"labels":{"i":"front"}},{"name":"right half","values":[2,5],"j":1,"used":[0],"labels":{"j":"front"}},{"name":"merged","values":[1,2,3,4]}]}}]},"options":[{"id":"copy","label":"It is copied to the end of the merged numbers","rationale":"Whatever is left on one side is already in order and at least as big as everything placed so far, so it is copied over as it stands. Then [1, 2, 3, 4, 5] is written back over the piece's positions in the list.","isCorrect":true},{"id":"compare","label":"It is compared with 4, the last number placed","rationale":"That comparison already happened: 4 was placed because it was smaller than 5. The left half has nothing more to compare with.","isCorrect":false},{"id":"drop","label":"Nothing, because the merge ends when one half runs out","rationale":"Stopping here would leave four numbers where the piece had five.","isCorrect":false}]},{"id":"return-total","kind":"case-probe","title":"The piece is counted and in order. What does it return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frame","state":{"nums":[1,2,3,4,5],"left half returned":2,"right half returned":1,"across":4}}]},"options":[{"id":"sum","label":"7, the three counts added together","rationale":"That is 2 pairs inside the left half, 1 inside the right half and 4 across the cut, and 2 + 1 + 4 = 7. This piece is the whole list, so the function returns 7, the same count checking every pair found.","isCorrect":true},{"id":"across-only","label":"4, the count across its own cut","rationale":"4 is only what this piece counted itself. The 3 pairs inside its halves reach the caller only if this piece adds them in.","isCorrect":false},{"id":"ordered-list","label":"[1, 2, 3, 4, 5], the ordered list","rationale":"The task asks how many pairs there are. Putting the numbers in order was a way to count faster, and the ordered numbers stay behind in the list.","isCorrect":false}]},{"id":"skip-merge-intro","kind":"info","title":"What if every piece counts and skips the merge?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frame","state":{"arrays":[{"name":"left half","values":[3,1,4]},{"name":"right half","values":[2,5]}]}}]},"body":["The function returns a count, and the count across a cut is finished before any merging starts. Suppose every piece counts across its cut and returns without merging, and [3, 1, 4, 2, 5] is run again."]},{"id":"skip-merge-pitfall","kind":"case-probe","title":"`j` moved past 2 while counting for 3, and `i` is now on 1. What does 1 add?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frame","state":{"arrays":[{"name":"left half","values":[3,1,4],"i":1},{"name":"right half","values":[2,5],"j":1,"used":[0]}],"across":1}}]},"options":[{"id":"missed-pair","label":"It adds 1, and the pair 1 with 2 is never counted","rationale":"Only 5 lies from `j` to the end, and 2 is already behind `j`, which never moves back. The count across the cut ends at 3, so the function returns 6 instead of 7. Leaving `j` in place only works when each left number is at least as big as the one before it, and [3, 1, 4] is out of order.","isCorrect":true},{"id":"goes-back","label":"It adds 2, because `j` moves back to 2","rationale":"`j` only ever moves forward. That is what keeps the count across a cut to a single trip through the right half.","isCorrect":false},{"id":"both-anyway","label":"It adds 2, because 1 is smaller than both right numbers","rationale":"Both pairs are real, but the count only runs from `j` to the end, and 2 is behind it.","isCorrect":false}]},{"id":"edge-case-intro","kind":"info","title":"With the merge in place, the plan counts all 7 pairs. Next, two lists of a different kind.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frame","state":{"nums":[2,2,2,5]}}]},"body":["The first is [2, 2, 2, 5], where one value repeats. The second is an empty list, with no numbers in it."]},{"id":"duplicates-probe","kind":"case-probe","title":"At the last cut of [2, 2, 2, 5], `i` is on a 2 and `j` is on an equal 2. How many pairs does this left 2 add?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frame","state":{"arrays":[{"name":"left half","values":[2,2],"i":0},{"name":"right half","values":[2,5],"j":0}]}}]},"options":[{"id":"skip-equal","label":"1","rationale":"A pair needs the earlier number to be smaller, and 2 is not smaller than 2. `j` moves past the equal 2 exactly as it moves past a smaller number, and only 5 is left to count.","isCorrect":true},{"id":"count-equal","label":"2","rationale":"That counts 2 with 2 as a pair, and equal numbers do not go up.","isCorrect":false},{"id":"tie-stops","label":"0","rationale":"The tie moves `j` one step and no further. 5 is still bigger than 2.","isCorrect":false}]},{"id":"empty-list-probe","kind":"case-probe","title":"The second list is empty: the piece from position 0 to position -1. Which stop rule covers it?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frame","state":{"nums":[],"lo":0,"hi":-1}}]},"options":[{"id":"at-or-past","label":"Stop when `lo` is at or past `hi`","rationale":"A single number has its two ends equal, and an empty list has its first end past its last. Both hold no pairs and return 0, so an empty list needs no separate check.","isCorrect":true},{"id":"equal-only","label":"Stop when `lo` equals `hi`","rationale":"0 does not equal -1, so the empty piece is cut. One of its halves is empty in the same way, and the cutting never ends.","isCorrect":false},{"id":"mid-at-lo","label":"Stop when the middle position is `lo`","rationale":"A piece of two numbers also has its middle at `lo`. It would return 0 without ever comparing them.","isCorrect":false}]},{"id":"ready-to-code","kind":"info","title":"Every part of the count is worked out. Now write the function.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"frame","state":{"nums":[3,1,4,2,5]}}]},"body":["The function works on pieces of the list, starting with the whole list. A piece with fewer than two numbers returns 0.","Any other piece is cut after its middle position, and each half is counted the same way. Both halves come back in order.","Then the piece counts the pairs across its cut. A marker moves forward through the right half, and each left number adds the right numbers from the marker to the end.","Last, the piece merges its halves into order and writes them back into the list. It returns the two halves' counts plus the count across its cut."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Count the increasing pairs","workspacePanel":"code"},{"id":"complete","kind":"complete","title":"Counting pairs one cut at a time","workspacePanel":"code","takeaways":[{"title":"Every pair belongs to one cut","body":"A pair is inside the left half, inside the right half or across the cut, so a piece returns those three counts added together and a single number returns 0."},{"title":"Ordered halves turn the across count into one trip","body":"Once a right number is bigger than a left number, every right number after it is too, and the marker never has to move back for the next left number."},{"title":"Merge after counting, and write the result back","body":"The piece above can only use a half that is in order in the list. Skipping the merge returned 6 for [3, 1, 4, 2, 5], where the true count is 7."},{"title":"O(n log n) time, O(n) extra space","body":"Each level of cuts does work in proportion to the n numbers it covers, and halving 100,000 numbers takes 17 levels. That is a few million steps, against about 5 billion comparisons for checking every pair. The extra space is the merged copy of a piece, which is as long as the whole list at the last merge."}]}],"slidesOrigin":"authored"}}
