{"id":"small-sum-of-array","title":"Small Sum of Array","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 its small sum.\n\nFor each index `i`, add `nums[i]` once for every later index `j` where `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":["smallSum"],"case":"worst","enforcement":"hard","reason":"Each merge-sort level counts cross-half contributions and merges the interval in linear time."}],"examples":[{"input":"nums = [1,3,4,2,5]","output":"16","explanation":"1 contributes four times, 3 contributes twice, 4 contributes once, and 2 contributes once."},{"input":"nums = [5,4,3]","output":"0","explanation":"No 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 smallSum(self, nums: list[int]) -> int:\n        # Your code here\n        pass","functionName":"smallSum","testCases":[{"id":"1","input":{"nums":[1,3,4,2,5]},"expected":16,"description":"Mixed order with several cross-half contributions."},{"id":"2","input":{"nums":[5,4,3]},"expected":0,"description":"Descending values never contribute."},{"id":"3","input":{"nums":[1,1,1]},"expected":0,"description":"Equal values are not strictly smaller."},{"id":"4","input":{"nums":[2,1,3]},"expected":3,"description":"Both 2 and 1 contribute to the final 3."},{"id":"5","input":{"nums":[]},"expected":0,"description":"An empty array has no pairs."},{"id":"6","input":{"nums":[1,2,3,4]},"expected":10,"description":"Every earlier value contributes to every greater later value."},{"id":"7","input":{"nums":[4,1,2,3]},"expected":4,"description":"The large first value contributes nothing, while 1 and 2 contribute later."},{"id":"h1","input":{"nums":[1,2,3]},"expected":4},{"id":"h2","input":{"nums":[3,1,2,4]},"expected":7},{"id":"h3","input":{"nums":[1,2,1,2]},"expected":3},{"id":"zeros-contribute-no-small-sum","input":{"nums":[0,3,0,2]},"expected":0,"description":"Zeros are valid values and contribute nothing smaller to later elements."},{"id":"topup-mixed-zero-growth","input":{"nums":[0,2,1,3]},"expected":3,"description":"Zero and mixed growth contribute only when earlier values are smaller."}],"hints":[{"level":1,"content":"A value contributes only when it is in the left half and smaller than values 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 a left value, every right-half value after the pointer is greater, so add `nums[i] * count` before merging."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which way of counting should the function use?","decisionPrompt":"The array can hold up to 100,000 numbers, so weigh how the work grows with its length.","approaches":[{"id":"nested-loops","name":"Compare every pair directly","summary":"For each number, scan every number after it and add the number whenever the later one is larger.","decisionReason":"Every number rescans everything after it, so 100,000 numbers take about 5 billion comparisons.","complexity":{"time":"O(n^2)","space":"O(1)"},"tradeoffs":["O(n^2) time and O(1) extra space."],"isOptimal":false},{"id":"merge-contribution","name":"Count across sorted halves while merge sorting","summary":"Find the small sum of each half, count the pairs that cross the cut with one forward pointer over the two sorted halves, then merge the halves.","decisionReason":"About 17 rounds of halving cover 100,000 numbers, and each round takes at most one pass over the numbers to count and one to merge.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["O(n log n) time, with O(n) extra space for the merge buffer."],"isOptimal":true}]},"codingCheckpoints":[{"id":"recursive-calls","title":"Split the range and total both halves","description":"Write a helper that takes a range of the array and returns that range's small sum. A range with fewer than two numbers returns 0. Any other range is split at its midpoint, and its total starts as the left half's result plus the right half's.","commonMistakes":["Stopping only when the range holds exactly one number, which never stops an empty array","Calling the helper on only one half, so the other half's pairs are never counted","Returning 1 for a range that holds one number"],"hint":"The two halves must not overlap, and between them they must cover the whole range.","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 interval 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-small-sum-recursive-calls","language":"python","code":"class Solution:\n    def smallSum(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-contribution","title":"Add the crossing pairs","description":"Both halves come back sorted. Go through the left half in order, moving one pointer through the right half past every value that is smaller than or equal to the current left value. Then add the left value once for each right-half value from the pointer to the end of the range.","commonMistakes":["Stopping the pointer on a value equal to the left value, which counts a value that is not larger","Sending the pointer back to the start of the right half for every left value, which brings back the repeated scans","Overwriting the total from the two halves instead of adding to it"],"hint":"Set the pointer to the start of the right half once, before the first left value, and let it carry over from one left value to the next.","semanticSpec":{"intent":"Count cross-half small-sum contribution before merging the two sorted halves.","doneWhen":"The code advances a right-half pointer past values `<= nums[i]` and adds `nums[i]` times the remaining right-half width.","shouldFailWhen":"This step should fail if the cross contribution is never added.","roles":["left scan","right boundary pointer","strict smaller comparison","weighted 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 greater later values.","Replacing the total instead of adding cross contributions to it."],"equivalentVariants":["Use one right pointer that only moves forward across the sorted right half."],"proofSnippets":[{"id":"py-small-sum-count-cross-contribution","language":"python","code":"class Solution:\n    def smallSum(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 += nums[i] * (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 array","description":"Merge the two sorted halves into a temporary buffer by taking the smaller front value each time. Copy over whatever is left on either side. Then write the buffer back over the same range of the array.","commonMistakes":["Writing the merged values back before the crossing pairs are added, which mixes the two halves","Leaving out the values that remain when one half runs out","Filling the buffer and never writing it back into the array"],"hint":"The range this one was cut from reads it as a sorted half when it counts its own crossing pairs.","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 contribution has been accumulated."],"equivalentVariants":["Use a temporary array and copy it back to `nums[lo:hi+1]`."],"proofSnippets":[{"id":"py-small-sum-merge-arrays","language":"python","code":"class Solution:\n    def smallSum(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 += nums[i] * (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 its range's total: the left half, the right half and the crossing pairs together. The function returns the helper's result for the range that covers the whole array.","commonMistakes":["Returning the sorted array, which is only a side effect of the counting","Returning only the crossing pairs of the last range"],"hint":"The whole array runs from its first position to its last, and an empty array is a range with fewer than two numbers.","semanticSpec":{"intent":"Return the total accumulated from left-half, right-half, and cross-half contributions.","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, the 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 contribution without recursive subtotals."],"equivalentVariants":["Return `total` from the helper and return the helper call over the full interval."],"proofSnippets":[{"id":"py-small-sum-return-total","language":"python","code":"class Solution:\n    def smallSum(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 += nums[i] * (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":"Add each number once for every larger number after it","workspacePanel":"problem","body":["You are given an array of numbers. Take each number in turn, count the numbers after it that are larger, and add it to a running total once for each one.","The finished total is called the small sum of the array, and it is what the function returns."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"four","title":"4 is added twice","summary":"After 4 come 1, 3, 5, 2 and 6, and only 5 and 6 are larger. The total starts at 8.","state":{"arrays":[{"name":"nums","values":[4,1,3,5,2,6],"current":0,"used":[1,2,4]}],"total":8}},{"id":"one","title":"1 is added four times","summary":"3, 5, 2 and 6 all come after 1 and are all larger, so the total reaches 12.","state":{"arrays":[{"name":"nums","values":[4,1,3,5,2,6],"current":1,"used":[0]}],"total":12}},{"id":"three","title":"3 is added twice","summary":"After 3 come 5, 2 and 6. Only 5 and 6 are larger than 3, so the total reaches 18.","state":{"arrays":[{"name":"nums","values":[4,1,3,5,2,6],"current":2,"used":[0,1,4]}],"total":18}},{"id":"five","title":"5 is added once","summary":"Of the two numbers after 5, only 6 is larger. The total reaches 23.","state":{"arrays":[{"name":"nums","values":[4,1,3,5,2,6],"current":3,"used":[0,1,2,4]}],"total":23}},{"id":"two","title":"2 is added once","summary":"6 is the only number after 2, and it is larger. The total reaches 25.","state":{"arrays":[{"name":"nums","values":[4,1,3,5,2,6],"current":4,"used":[0,1,2,3]}],"total":25}},{"id":"six","title":"6 is never added","summary":"Nothing comes after 6, so the small sum of this array is 25. Counting number by number like this is the direct count, and here it made 15 comparisons.","state":{"arrays":[{"name":"nums","values":[4,1,3,5,2,6],"current":5,"used":[0,1,2,3,4]}],"total":25}}]}},{"id":"cost-probe","kind":"case-probe","title":"The six numbers took 15 comparisons. How many would twelve numbers take?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"direct-count-done","state":{"arrays":[{"name":"nums","values":[4,1,3,5,2,6]}],"comparisons":15}}]},"options":[{"id":"doubles","label":"30, since twice as many numbers means twice as many comparisons","rationale":"The scans get longer as well as more numerous: the first of twelve numbers is compared with eleven others, where the first of six was compared with five.","isCorrect":false},{"id":"every-later-number","label":"66, since every number is compared with every number after it","rationale":"The first number is compared with the 11 after it, the next with 10, and so on down to 1, which makes 66. Doubling the array more than quadrupled the work. At 100,000 numbers, the most the array can hold, it is about 5 billion comparisons.","isCorrect":true},{"id":"adds-six","label":"21, since six more numbers add six more comparisons","rationale":"Each added number is compared with every number already in the array, so the twelfth alone adds eleven comparisons.","isCorrect":false}]},{"id":"sorted-run-probe","kind":"case-probe","title":"Suppose the numbers after 1 were sorted: 2, 3, 5, 6. How many comparisons does it take to know how many times 1 is added?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"after-one-sorted","state":{"arrays":[{"name":"nums","values":[4,1,3,5,2,6],"current":1},{"name":"after 1, sorted","values":[2,3,5,6],"current":0}]}}]},"options":[{"id":"one","label":"One: 1 against 2","rationale":"1 is smaller than 2, and in ascending order 3, 5 and 6 are at least 2, so all four are larger than 1. In the array as given, the direct count needs four comparisons to learn the same thing.","isCorrect":true},{"id":"four","label":"Four: 1 against each of them","rationale":"The order already says 3, 5 and 6 are at least 2. Once 1 is smaller than 2, it is smaller than all of them.","isCorrect":false},{"id":"two","label":"Two: 1 against 2 and against 6","rationale":"6 comes after 2 in ascending order, so it is at least 2. Comparing it with 1 shows nothing the first comparison did not.","isCorrect":false}]},{"id":"cut-in-half","kind":"info","title":"Cut the array in half and every pair lands in one of three places","workspacePanel":"visualizer","body":["Call a smaller number with a larger number after it a pair. The small sum adds the smaller number once for every pair it is in.","Sorting the whole array would save comparisons like that, but it moves numbers past each other. Sorted, 4, 1, 3, 5, 2, 6 reads 1, 2, 3, 4, 5, 6, and its small sum would be 35, where the answer is 25.","So cut the array down the middle instead. Both numbers of a pair are then in the left half, both in the right half, or one on each side of the cut."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"inside-left","title":"Both in the left half","summary":"1 comes before 3 and is smaller, and both are left of the cut.","state":{"arrays":[{"name":"left half","values":[4,1,3],"used":[0]},{"name":"right half","values":[5,2,6],"used":[0,1,2]}]}},{"id":"inside-right","title":"Both in the right half","summary":"5 comes before 6 and is smaller, and both are right of the cut.","state":{"arrays":[{"name":"left half","values":[4,1,3],"used":[0,1,2]},{"name":"right half","values":[5,2,6],"used":[1]}]}},{"id":"crossing","title":"One on each side","summary":"4 is in the left half and 5 is in the right half. A pair like this is a crossing pair.","state":{"arrays":[{"name":"left half","values":[4,1,3],"used":[1,2]},{"name":"right half","values":[5,2,6],"used":[1,2]}]}}]}},{"id":"crossing-pairs","kind":"case-probe","title":"This time only the right half is sorted. Which pairs can change?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"right-half-sorted","state":{"arrays":[{"name":"left half","values":[4,1,3]},{"name":"right half","values":[5,2,6]},{"name":"right half, sorted","values":[2,5,6]}]}}]},"options":[{"id":"crossing","label":"Only the crossing pairs","rationale":"A crossing pair has its smaller number on the left and its larger number on the right. Sorting the right half keeps both on their own sides, so 4 still pairs with 5 and with 6.","isCorrect":false},{"id":"inside-right","label":"Only the pairs inside the right half","rationale":"Sorting moves numbers only within the right half. 5 came before 2, so they were never a pair, and now 2 comes before 5 and they look like one. Every left-half number is still before every right-half number.","isCorrect":true},{"id":"any-with-right","label":"Every pair with a number in the right half","rationale":"That includes crossing pairs such as 4 and 5, and those are untouched: every left-half number still comes before every right-half number.","isCorrect":false}]},{"id":"sorted-halves","kind":"info","title":"Sort both halves, then count the crossing pairs","workspacePanel":"visualizer","body":["Sorting the left half leaves the crossing pairs alone for the same reason. So put both halves in ascending order, and call what the crossing pairs add the crossing sum.","`i` marks the left value being counted, smallest first, and `j` is the pointer that walks the right half.","Sorting can change the pairs inside a half, so those have to be counted before the half is sorted."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"both-sorted","state":{"arrays":[{"name":"left half","values":[1,3,4],"i":0},{"name":"right half","values":[2,5,6],"j":0}],"crossing sum":0}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Count the crossing pairs","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup","state":{"arrays":[{"name":"left half","values":[1,3,4],"i":0},{"name":"right half","values":[2,5,6],"j":0}],"crossing sum":0}},{"id":"one-adds","state":{"arrays":[{"name":"left half","values":[1,3,4],"i":1},{"name":"right half","values":[2,5,6],"j":0}],"crossing sum":3}},{"id":"three-adds","state":{"arrays":[{"name":"left half","values":[1,3,4],"i":2},{"name":"right half","values":[2,5,6],"j":1,"used":[0]}],"crossing sum":9}},{"id":"four-starts","state":{"arrays":[{"name":"left half","values":[1,3,4],"i":2},{"name":"right half","values":[2,5,6],"j":1,"used":[0]}],"crossing sum":17}}]},"beats":[{"id":"one-adds","title":"How much does 1 add to the crossing sum?","options":[{"id":"once","label":"1, added once for the 2 under the pointer","rationale":"2 is only the first larger value. 5 and 6 follow it in ascending order, so 1 pairs with them too.","isCorrect":false},{"id":"three-times","label":"3, added once each for 2, 5 and 6","rationale":"1 is smaller than 2. The right half is ascending, so 5 and 6 are larger than 2 and larger than 1 as well.","isCorrect":true},{"id":"sum-of-right","label":"13, the sum of 2, 5 and 6","rationale":"A pair adds its smaller number, and that is 1 in all three pairs. 2, 5 and 6 only decide how many times 1 is added.","isCorrect":false}]},{"id":"three-adds","title":"The left value is now 3. How much does it add to the crossing sum?","options":[{"id":"all-three","label":"9, added once each for 2, 5 and 6","rationale":"2 is smaller than 3. A pair needs its larger number on the right, so 2 does not count.","isCorrect":false},{"id":"first-larger-only","label":"3, added once for 5, the first larger value","rationale":"6 comes after 5 in ascending order, so it is larger than 3 too. 3 is added for both.","isCorrect":false},{"id":"five-and-six","label":"6, added once each for 5 and 6","rationale":"2 is smaller than 3, so the pointer moves past it. 5 is larger, and 6 follows 5, so 3 is added for both. The pointer is checked first and moves past every value that is too small. The left value is then added once for each value left.","isCorrect":true}]},{"id":"four-starts","title":"The left value is now 4. Where does the pointer have to start?","options":[{"id":"stays","label":"On 5, where it stopped for 3","rationale":"4 is larger than 3, so the 2 that was too small for 3 is too small for 4 as well. 5 is larger than 4, so 4 is added twice, and the crossing sum is 3 + 6 + 8 = 17. That took four comparisons, where the direct count spends nine on the same pairs.","isCorrect":true},{"id":"rewinds","label":"Back on 2, the start of the right half","rationale":"2 was not larger than 3, and 4 is larger than 3, so 2 cannot be larger than 4.","isCorrect":false},{"id":"skips-ahead","label":"On 6, one past where it stopped for 3","rationale":"Stopping on 5 showed that 5 is larger than 3. It says nothing about 4, so 5 still has to be compared with 4.","isCorrect":false}]}]},{"id":"inside-pairs","kind":"case-probe","title":"The crossing sum is 17. How should the pairs inside the left half be counted?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"halves-as-given","state":{"arrays":[{"name":"left half","values":[4,1,3]},{"name":"right half","values":[5,2,6]}],"crossing sum":17}}]},"options":[{"id":"direct","label":"Compare each of its numbers with every number after it","rationale":"That is the direct count again. On a half of 50,000 numbers it still takes more than a billion comparisons.","isCorrect":false},{"id":"repeat","label":"Treat it as a smaller array and repeat the same procedure","rationale":"Cutting 4, 1, 3 gives pairs inside its two pieces and pairs crossing between them, the same three places as before.","isCorrect":true},{"id":"already-counted","label":"Nothing more is needed, since the crossing sum included them","rationale":"The crossing sum only paired a left-half number with a right-half number. 1 and 3 are both in the left half.","isCorrect":false}]},{"id":"cut-down","kind":"info","title":"The left half is cut again, down to single numbers","workspacePanel":"visualizer","body":["Three numbers cannot be cut evenly, so one side takes two."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"left-half-as-given","title":"The left half, as it was given","summary":"4, 1, 3 has not been sorted yet, so the pairs inside it are intact.","state":{"arrays":[{"name":"left half","values":[4,1,3]}]}},{"id":"first-cut","title":"4, 1, 3 becomes 4, 1 and 3","summary":"4, 1 still holds two numbers, so it is cut again.","state":{"arrays":[{"name":"left side","values":[4,1]},{"name":"right side","values":[3]}]}},{"id":"second-cut","title":"4, 1 becomes 4 and 1","summary":"3 is already a single number, so it waits while 4, 1 is cut.","state":{"arrays":[{"name":"left side","values":[4]},{"name":"right side","values":[1]},{"name":"waiting","values":[3]}]}}]}},{"id":"left-half-trace","kind":"dry-run","source":"trace-example","title":"Count the left half from single numbers up","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup","state":{"arrays":[{"name":"left side","values":[4],"current":0},{"name":"right side","values":[1]},{"name":"waiting","values":[3]}]}},{"id":"single-four","state":{"arrays":[{"name":"left side","values":[4],"i":0},{"name":"right side","values":[1],"j":0},{"name":"waiting","values":[3]}],"crossing sum":0}},{"id":"four-against-one","state":{"arrays":[{"name":"left side","values":[4]},{"name":"right side","values":[1],"used":[0]},{"name":"waiting","values":[3]}],"small sum":0}},{"id":"hand-back","state":{"arrays":[{"name":"left side","values":[1,4],"i":0},{"name":"right side","values":[3],"j":0}],"crossing sum":0}},{"id":"one-four-against-three","state":{"arrays":[{"name":"left side","values":[1,4],"i":1},{"name":"right side","values":[3],"used":[0]}],"crossing sum":1}},{"id":"merge","state":{"arrays":[{"name":"left half","values":[1,3,4]}],"small sum":1}}]},"beats":[{"id":"single-four","title":"What is the small sum of the piece that holds only 4?","options":[{"id":"itself","label":"4, the one number in the piece","rationale":"A number is added once per larger number after it. 4 has none in this piece, so it is never added.","isCorrect":false},{"id":"zero","label":"0, since nothing comes after 4 in the piece","rationale":"A number is added only for a larger number after it, and this piece has nothing after 4.","isCorrect":true},{"id":"one","label":"1, since the piece holds one number","rationale":"The small sum is a total of added numbers. With no pair in the piece, nothing is added.","isCorrect":false}]},{"id":"four-against-one","title":"The piece holding only 1 also returns 0. Now 4 and 1 meet across their cut. How much does 4 add to the crossing sum?","options":[{"id":"zero","label":"0, since the pointer passes 1 and runs out of values","rationale":"1 is not larger than 4, so the pointer moves past it and off the end of the right side. No values remain, and 4 is added zero times.","isCorrect":true},{"id":"four","label":"4, added once for the 1 under the pointer","rationale":"1 is smaller than 4. A pair needs its larger number on the right, and the right side has none.","isCorrect":false},{"id":"one","label":"1, the smaller of the two numbers","rationale":"1 comes after 4 in the array. A pair has its smaller number first, so 4 and 1 are not a pair at all.","isCorrect":false}]},{"id":"hand-back","title":"The piece 4, 1 has its small sum, 0. What else does the next count, against 3, need from it?","options":[{"id":"as-given","label":"Its numbers in their original order: 4, 1","rationale":"Read as 4 then 1, the pointer would pass 3 while 4 is the left value, and 1 would then miss its pair with 3.","isCorrect":false},{"id":"nothing","label":"Nothing more: the small sum is all that gets used","rationale":"The next crossing count pairs these numbers with 3. It gets the right answer only if both sides arrive sorted.","isCorrect":false},{"id":"sorted","label":"Its numbers in ascending order: 1, 4","rationale":"4, 1 becomes the left side of the next crossing count, against 3, and that count reads both sides in ascending order. The pairs inside 4, 1 are already counted, so sorting it loses nothing.","isCorrect":true}]},{"id":"one-four-against-three","title":"What is the crossing sum of 1, 4 against 3?","options":[{"id":"both","label":"5, with 1 and 4 each added once","rationale":"4 is larger than 3, so 4 and 3 are not a pair. Only 1 is added.","isCorrect":false},{"id":"only-one","label":"1, with 1 added once and 4 never","rationale":"3 is larger than 1, so 1 is added once. When the left value becomes 4, the pointer passes 3 and runs out of values. 1 with 3 is the only pair inside the left half, so its small sum is 1.","isCorrect":true},{"id":"larger-number","label":"3, the larger number of the pair 1 and 3","rationale":"A pair adds its smaller number. For 1 and 3 that is 1.","isCorrect":false}]},{"id":"merge","title":"1, 4 and 3 have to become one ascending run. How should it be built?","options":[{"id":"take-smaller-front","label":"Keep taking the smaller of the two front values","rationale":"Both sides are ascending, so the smallest value left is always at one of the two fronts: 1, then 3, then 4. When one side runs out, the rest of the other is taken as it stands, and the run is written back into the array.","isCorrect":true},{"id":"sort-from-scratch","label":"Sort all three values from scratch","rationale":"1, 4 is already in order. Sorting from scratch ignores that and redoes the work in every piece.","isCorrect":false},{"id":"end-to-end","label":"Put the right side after the left side","rationale":"That gives 1, 4, 3, which is not ascending. The next crossing count would read it in the wrong order.","isCorrect":false}]}]},{"id":"whole-array-total","kind":"case-probe","title":"The right half returns 7 by the same steps. What is the small sum of the whole array?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"three-sums","state":{"arrays":[{"name":"left half","values":[1,3,4]},{"name":"right half","values":[2,5,6]}],"left small sum":1,"right small sum":7,"crossing sum":17}}]},"options":[{"id":"crossing-only","label":"17, the crossing sum, which is computed last","rationale":"17 covers only pairs with one number on each side. The pair 1 and 3 inside the left half is not in it.","isCorrect":false},{"id":"halves-only","label":"8, the small sums the two halves returned","rationale":"1 + 7 leaves out every pair that crosses the cut, such as 4 and 5.","isCorrect":false},{"id":"all-three","label":"25, both small sums plus the crossing sum","rationale":"1 for the pair inside the left half, 7 for the pairs inside the right half and 17 for the crossing pairs: 1 + 7 + 17 = 25. That is the same 25 the direct count reached.","isCorrect":true}]},{"id":"rounds-of-cutting","kind":"case-probe","title":"Six numbers took three rounds of cutting to reach single numbers. About how many rounds do 100,000 numbers take?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"three-rounds","state":{"arrays":[{"name":"nums","values":[4,1,3,5,2,6]}],"rounds of cutting":3}}]},"options":[{"id":"one-per-number","label":"About 100,000, one round for each number","rationale":"Six numbers needed three rounds. Each round halves every piece, so the rounds grow much more slowly than the numbers.","isCorrect":false},{"id":"halving","label":"About 17, since each round halves the pieces","rationale":"100,000 becomes 50,000, then 25,000, and after 17 halvings every piece is a single number. Each round's work is proportional to the length of the array, so 17 rounds come to a few million steps, against about 5 billion comparisons for the direct count.","isCorrect":true},{"id":"half-as-many","label":"About 50,000, half as many rounds as numbers","rationale":"A round cuts every piece in half at once, so the piece size falls far faster than one or two numbers per round.","isCorrect":false}]},{"id":"edge-inputs","kind":"info","title":"Before writing the code, try the same steps on two more arrays","workspacePanel":"visualizer","body":["The first is 1, 2, 2, 3, which puts a 2 on each side of the cut. The second is an empty array."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"repeated-value","state":{"arrays":[{"name":"nums","values":[1,2,2,3]}]}}]}},{"id":"equal-values-pitfall","kind":"case-probe","title":"In 1, 2, 2, 3, both halves hold a 2. What should the pointer do with the 2 it is on?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"equal-values-meet","state":{"arrays":[{"name":"left half","values":[1,2],"i":1},{"name":"right half","values":[2,3],"j":0}],"crossing sum":2}}]},"options":[{"id":"stay","label":"Stay on it, because 2 is not smaller than 2","rationale":"From this 2 to the end there are two values, so the left 2 would be added twice. Only 3 is larger, and the crossing sum would come out 2 too high.","isCorrect":false},{"id":"step-past","label":"Move past it, because 2 is not larger than 2","rationale":"2 is not larger than 2, so the pointer passes it, as it passes every right value that is smaller or equal. With the pointer on 3, one value remains, and the left 2 is added once.","isCorrect":true},{"id":"skip-both","label":"Move past it and past 3 as well","rationale":"3 is larger than 2, so they are a pair. Passing 3 leaves that pair uncounted.","isCorrect":false}]},{"id":"empty-array","kind":"case-probe","title":"The second array is empty and has to return 0. Which rule for stopping the cutting works for every array?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-numbers","state":{"arrays":[{"name":"nums","values":[]}]}}]},"options":[{"id":"exactly-one","label":"Stop when a piece has exactly one number","rationale":"An empty array never has exactly one number, so this rule never stops it.","isCorrect":false},{"id":"no-numbers","label":"Stop when a piece has no numbers","rationale":"It stops the empty array, but a one-number piece would then be cut into itself and an empty piece, and the cutting would never end.","isCorrect":false},{"id":"fewer-than-two","label":"Stop when a piece has fewer than two numbers","rationale":"Zero is fewer than two, so the empty array stops at once and returns 0, the same way a single number does. No separate check for an empty array is needed.","isCorrect":true}]},{"id":"ready-to-code","kind":"info","title":"That covers every step of the small sum. Next comes the code.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["The function finds the small sum of a range of the array, starting with the whole array. A range with fewer than two numbers returns 0.","Any other range is cut at its midpoint, and each half's small sum is found 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. The pointer passes every value that is not larger, and the left value is added once for each value from the pointer to the end.","Last, the range merges its halves into a buffer and writes them back. It returns the two halves' small sums plus its crossing sum."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"array-as-given","state":{"arrays":[{"name":"nums","values":[4,1,3,5,2,6]}]}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Write the small sum","workspacePanel":"code"},{"id":"complete","kind":"complete","title":"Small sum: sort the halves, then count across the cut","workspacePanel":"code","takeaways":[{"title":"Count first, merge last","body":"Merging a piece's halves can change the pairs inside the piece, so the crossing pairs between its halves are counted first and the merge comes last. Pairs that reach outside the piece keep their order either way."},{"title":"Sorted halves need one forward pass","body":"With both halves ascending, the pointer only moves forward through the right half, and each left value is added once for every right value from the pointer to the end."},{"title":"Equal values add nothing","body":"The pointer moves past right values that are smaller than or equal to the left value, so only strictly larger values are counted."},{"title":"O(n log n) time, O(n) space","body":"About log n rounds of halving each take at most one pass over the n numbers to count and merge, and the merge uses a temporary buffer of up to n numbers. The direct count is O(n^2) time and O(1) space."}]}],"slidesOrigin":"authored","progressRevision":"small-sum-of-array-2026-11-20-count-across-sorted-halves"}}
