{"id":"minimum-adjacent-swaps-to-sort","title":"Minimum Adjacent Swaps to Sort","difficulty":"medium","patterns":["sorting-divide-conquer"],"primaryConcept":"sorting-divide-conquer","concepts":["sorting-divide-conquer"],"problemForm":"application","companies":["Google","Amazon","Meta","Microsoft"],"category":"searching-sorting","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"nums","sizeMetric":"array-length","constraints":["integers"],"sizes":[8,16,32,64]},"description":"Given an integer array `nums`, return the minimum number of adjacent swaps needed to sort the array in nondecreasing order.\n\nAn adjacent swap exchanges two neighboring elements. Equal values do not need to swap past each other.\n\nUse a merge-sort based inversion count. Do not use the O(n^2) nested-loop approach.","requiredComplexity":[{"metric":"time","bound":"O(n log n)","scope":"function","functions":["minimumAdjacentSwapsToSort"],"case":"worst","enforcement":"hard","reason":"Each merge-sort level counts cross-half inversions and merges the interval in linear time."}],"examples":[{"input":"nums = [3,1,2]","output":"2","explanation":"Swap 3 past 1 and 2 to reach [1,2,3]."},{"input":"nums = [2,4,1,3,5]","output":"3","explanation":"The inverted pairs are (2,1), (4,1), and (4,3)."}],"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}}],"starterCode":"class Solution:\n    def minimumAdjacentSwapsToSort(self, nums: list[int]) -> int:\n        # Your code here\n        pass","functionName":"minimumAdjacentSwapsToSort","testCases":[{"id":"1","input":{"nums":[3,1,2]},"expected":2,"description":"One value moves across two smaller values."},{"id":"2","input":{"nums":[1,2,3]},"expected":0,"description":"Already sorted array needs no swaps."},{"id":"3","input":{"nums":[4,3,2,1]},"expected":6,"description":"Every pair is inverted."},{"id":"4","input":{"nums":[2,4,1,3,5]},"expected":3,"description":"Mixed inversions across the merge boundary."},{"id":"5","input":{"nums":[2,1,2]},"expected":1,"description":"Equal values do not count as inverted."},{"id":"h1","input":{"nums":[5]},"expected":0,"description":"Single value is already sorted."},{"id":"h2","input":{"nums":[5,1,4,2,3]},"expected":6,"description":"Several cross-half inversions."},{"id":"h3","input":{"nums":[-1,-3,-2,0]},"expected":2,"description":"Negative values still compare normally."},{"id":"h4","input":{"nums":[3,3,2,2]},"expected":4,"description":"Duplicates only count when the left value is strictly greater."},{"id":"h5","input":{"nums":[1,5,3,4,2]},"expected":5,"description":"Late small values create multiple adjacent swaps."},{"id":"topup-duplicate-stable-inversions","input":{"nums":[3,1,2,1]},"expected":4,"description":"Duplicates require stable adjacent swaps into sorted order."},{"id":"topup-already-sorted","input":{"nums":[1,2,3,4,5]},"expected":0,"description":"Already sorted input needs no adjacent swaps."}],"hints":[{"level":1,"content":"Every adjacent swap fixes exactly one inverted pair."},{"level":2,"content":"During merge, if a right-half value is smaller than a left-half value, it must pass every remaining left-half value."},{"level":3,"content":"Add `mid - left + 1` when choosing the right value before the remaining left half."}],"guidedFlow":{"version":2,"progressRevision":"minimum-adjacent-swaps-to-sort-2026-11-20-pairs-then-merges","approachSelection":{"contract":"approach-selection-v1","question":"Which way of counting stays fast on an array of 100,000 values?","decisionPrompt":"Compare how many steps each approach takes as the array grows.","approaches":[{"id":"simulate-swaps","name":"Swap neighbors until sorted","summary":"Sweep the array, swap every neighboring pair that is out of order, and count the swaps.","decisionReason":"Each swap fixes one out-of-order pair, and a reversed array of 100,000 values has just under 5 billion of them, so the swapping alone takes O(n^2) steps.","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":"Sort each half recursively and, while merging the halves, add the number of left-half values each right-half value passes.","decisionReason":"A sorted left half lets one comparison count every value a right-half value passes, so each level of merging takes O(n) steps and there are about log n levels.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["O(n log n) time and O(n) extra space for the merged list."],"isOptimal":true}]},"codingCheckpoints":[{"id":"merge-sort-helper","title":"Write the helper for one piece","description":"Write a helper that works on one piece of the array, given where the piece starts and ends. A piece with one value or none has no pairs inside it, so the helper returns 0 for it right away. For anything longer, find the middle position, where the piece will be cut.","commonMistakes":["Stopping only when the piece is empty, so a one-value piece keeps cutting itself forever","Returning the piece itself when the helper should return a count"],"hint":"A piece whose start has reached its end holds at most one value, and there is nothing in it to compare.","semanticSpec":{"intent":"Create the recursive interval-counting shell.","doneWhen":"The helper stops on collapsed intervals and splits by midpoint.","shouldFailWhen":"This step should fail if there is no recursive interval helper.","roles":["left bound","right bound","midpoint"],"mustProve":["Collapsed intervals return zero."],"mustNotAccept":["Flat nested-loop counting."],"equivalentVariants":["Use inclusive or half-open interval bounds if the base case is equivalent."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sequence-ordering","fact":"short_circuits_collapsed_interval_with_zero_return","scope":"base-case","readMode":"legacy-fact-query-v1"}]}},{"id":"recursive-calls","title":"Count inside each half","description":"Call the helper on the left half and on the right half of the piece, and start this piece's count from the sum of what the two calls return.","commonMistakes":["Calling the helper on one half only","Dropping what the two calls return, so only the pairs across the cut get counted"],"hint":"Each call does two jobs: it sorts its half and it reports the out-of-order pairs inside that half. Both reports belong in the total.","semanticSpec":{"intent":"Split the interval recursively and combine child counts.","doneWhen":"The helper calls itself on both midpoint halves.","shouldFailWhen":"This step should fail if either half is skipped.","roles":["recursive helper","left interval","right interval"],"mustProve":["Both midpoint subintervals are processed recursively."],"mustNotAccept":["Sorting only one side before merge."],"equivalentVariants":["Store child results separately or add them directly."]},"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-swaps","title":"Count the pairs across the cut","description":"While merging, compare the two front values. Whenever the right front is strictly smaller than the left front, add the number of left-half values that have not been placed yet.","commonMistakes":["Adding 1 each time a right-half value is placed, which misses the values behind the left front","Adding the full size of the left half, which also counts values that were already placed","Counting a tie as a pass, when two equal values never need to swap"],"hint":"The left half is sorted, so a right-half value that is smaller than the left front is smaller than everything from that front to the end of the left half.","semanticSpec":{"intent":"Update the accumulated swap count from merge comparisons.","doneWhen":"The accumulator increases when a right-half value must move before remaining left-half values.","shouldFailWhen":"This step should fail if the merge never updates the count.","roles":["swap count","left pointer","right pointer"],"mustProve":["The scalar accumulator is additively updated inside the merge logic."],"mustNotAccept":["Counting without using the merge boundary."],"equivalentVariants":["Use `mid - left + 1` or an equivalent remaining-left count."]},"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 and write the result back","description":"Build the sorted order by taking the smaller front value each time, with the left value first on a tie. When one half runs out, the rest of the other half follows. Then write the sorted order back over this piece of the array.","commonMistakes":["Counting without writing the sorted order back, which leaves an unsorted piece for the next merge","Stopping when one half runs out and losing the values still waiting in the other half"],"hint":"This piece is merged into a longer piece next, and the counting there is only right if this piece sits in the array in sorted order.","semanticSpec":{"intent":"Restore sorted interval order for parent merge levels.","doneWhen":"The code merges both halves, flushes remainders, and writes the buffer back.","shouldFailWhen":"This step should fail if the sorted interval is not written back.","roles":["left pointer","right pointer","temporary buffer"],"mustProve":["The merge writes a sorted buffer back into the source interval."],"mustNotAccept":["Counting without merging."],"equivalentVariants":["Use a temporary list or array."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sequence-ordering","fact":"merges_sorted_intervals_with_writeback","scope":"merge-arrays","readMode":"sequence-ordering-value-query-v1"}]}},{"id":"return-count","title":"Return the count for the whole array","description":"The helper returns the total for its piece: the counts from its two halves plus the pairs it found across the cut. The function returns what the helper reports for the piece that covers all of `nums`.","commonMistakes":["Returning the sorted array when the answer is a number","Returning only the pairs found in the last merge"],"hint":"The first call covers the array from its first position to its last.","semanticSpec":{"intent":"Return the terminal scalar accumulator.","doneWhen":"The method returns the accumulated count from the full array interval.","shouldFailWhen":"This step should fail if the final result is not the accumulated count.","roles":["swap count","full interval"],"mustProve":["The terminal accumulator is returned."],"mustNotAccept":["Returning the sorted array instead of the count."],"equivalentVariants":["Store the helper result in a variable before returning it."]},"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":"Sort an array with the fewest swaps of neighbors","workspacePanel":"problem","body":["You are given an array of integers. One move swaps two values that sit next to each other.","Return the smallest number of moves that leaves the array sorted from smallest to largest. Two equal values never need to trade places."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"as-given","title":"The array as given","state":{"nums":[4,2,3,1],"swaps":0}},{"id":"swap-1","title":"Swap 4 and 2","state":{"nums":[2,4,3,1],"left":0,"right":1,"labels":{"left":"","right":""},"swaps":1}},{"id":"swap-2","title":"Swap 4 and 3","state":{"nums":[2,3,4,1],"left":1,"right":2,"labels":{"left":"","right":""},"swaps":2}},{"id":"swap-3","title":"Swap 4 and 1","state":{"nums":[2,3,1,4],"left":2,"right":3,"labels":{"left":"","right":""},"swaps":3}},{"id":"swap-4","title":"Swap 3 and 1","state":{"nums":[2,1,3,4],"left":1,"right":2,"labels":{"left":"","right":""},"swaps":4}},{"id":"swap-5","title":"Swap 2 and 1","state":{"nums":[1,2,3,4],"left":0,"right":1,"labels":{"left":"","right":""},"swaps":5}},{"id":"sorted","title":"Sorted in 5 swaps","summary":"No sequence of neighbor swaps sorts this array in fewer than 5, so for this array the function returns 5.","state":{"nums":[1,2,3,4],"swaps":5}}]}},{"id":"one-swap-one-pair","kind":"case-probe","title":"The first swap traded 4 and 2. Which pairs changed their order?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-swap","state":{"arrays":[{"name":"before","values":[4,2,3,1]},{"name":"after","values":[2,4,3,1]}]}}]},"options":[{"id":"only-the-swapped-pair","label":"Only the pair 4 and 2","rationale":"3 and 1 did not move, and 4 and 2 are both still to the left of them. So a neighbor swap changes the order of only the two values it touches, and one swap can fix at most one out-of-order pair.","isCorrect":true},{"id":"pairs-with-four","label":"Every pair that includes 4","rationale":"4 is still to the left of 3 and of 1, the same as before the swap. Its order changed against 2 and against nothing else.","isCorrect":false},{"id":"every-pair","label":"Every pair in the array","rationale":"3 is still ahead of 1, and both are still behind 4 and 2. Five of the six pairs kept their order.","isCorrect":false}]},{"id":"count-the-pairs","kind":"case-probe","title":"Take any two values, neighbors or not. In how many pairs does the larger one come first?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"the-array","state":{"nums":[4,2,3,1]}}]},"options":[{"id":"three-pairs","label":"3 pairs","rationale":"That counts only the pairs that start with 4. 2 before 1 and 3 before 1 have the larger value first too.","isCorrect":false},{"id":"five-pairs","label":"5 pairs","rationale":"4 is ahead of 2, 3 and 1, and 2 and 3 are each ahead of 1. That is five pairs, and the array took five swaps. A swap fixes at most one such pair, and an unsorted array always has two neighbors whose swap fixes one, so the fewest swaps always equals this count.","isCorrect":true},{"id":"six-pairs","label":"6 pairs","rationale":"Four values form 6 pairs in all, and one of them, 2 before 3, is already in order.","isCorrect":false}]},{"id":"waste-probe","kind":"case-probe","title":"Four values make 6 pairs to check. About how many pairs do 100,000 values make?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"the-array","state":{"nums":[4,2,3,1]}}]},"options":[{"id":"linear","label":"About 100,000","rationale":"That is one pair per value. The first value alone forms 99,999 pairs.","isCorrect":false},{"id":"quadratic","label":"About 5 billion","rationale":"The first value has 99,999 partners, the next has 99,998, and so on down to 1. That adds up to 100,000 × 99,999 / 2, just under 5 billion. Arrays this long are allowed, so the count has to come from far fewer comparisons than there are pairs.","isCorrect":true},{"id":"n-log-n","label":"About 10 billion","rationale":"That is 100,000 × 100,000, which counts each pair twice and pairs every value with itself.","isCorrect":false}]},{"id":"split-the-pairs","kind":"case-probe","title":"Cut the array in half. How many of the 5 out-of-order pairs have one value in each half?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-halves","state":{"arrays":[{"name":"left half","values":[4,2]},{"name":"right half","values":[3,1]}]}}]},"options":[{"id":"one-across","label":"1 pair","rationale":"One pair is what each half holds inside itself: 4 before 2 on the left, 3 before 1 on the right.","isCorrect":false},{"id":"three-across","label":"3 pairs","rationale":"4 before 3, 4 before 1 and 2 before 1 each take one value from each half. The other two sit one inside each half, so 5 = 1 + 1 + 3. Counting inside a half is the same question on a shorter array, so the same cut works there.","isCorrect":true},{"id":"five-across","label":"5 pairs","rationale":"Two of the five never cross the cut: 4 before 2 sits inside the left half and 3 before 1 inside the right half.","isCorrect":false}]},{"id":"single-value-piece","kind":"case-probe","title":"Cut the left half again and each piece holds one value. How many out-of-order pairs are inside a one-value piece?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-pieces","state":{"arrays":[{"name":"left piece","values":[4]},{"name":"right piece","values":[2]}]}}]},"options":[{"id":"none-inside","label":"None","rationale":"A pair needs two values, so a one-value piece holds none, and it is already sorted. That is where the cutting stops: a one-value piece reports 0, and every longer piece adds its two halves' counts to the pairs across its own cut.","isCorrect":true},{"id":"one-inside","label":"One","rationale":"The pair 4 before 2 has one value in each piece, so it lies across this cut. Neither piece holds it inside.","isCorrect":false},{"id":"depends-on-value","label":"It depends on the value","rationale":"Whatever the value is, it has no partner inside its own piece.","isCorrect":false}]},{"id":"sort-halves-first","kind":"case-probe","title":"Sort each half on its own. How many out-of-order pairs cross the cut now?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"sorted-halves","state":{"arrays":[{"name":"left half, sorted","values":[2,4]},{"name":"right half, sorted","values":[1,3]}]}}]},"options":[{"id":"none-across","label":"None: sorting put them in order","rationale":"Sorting a half fixes only the pairs inside it. 4 is still ahead of 1 and of 3, and 2 is still ahead of 1.","isCorrect":false},{"id":"two-across","label":"2: moving 4 back fixed one","rationale":"4 moved one place inside the left half and is still ahead of both right-half values, 3 and 1.","isCorrect":false},{"id":"still-three","label":"Still 3: no value moved across the cut","rationale":"Sorting a half only reorders values inside it, so every left-half value stays ahead of every right-half value. The same three pairs cross the cut.","isCorrect":true}]},{"id":"dry-run-setup","kind":"info","title":"The same 5 has to come out of cutting and merging","workspacePanel":"visualizer","body":["So each half can be sorted first, counting its own inside pairs as it goes, and the 3 pairs across the cut are still there to count afterward.","Each piece is sorted by merging its two sorted halves: take the smaller of the two front values, again and again, into a new list.","A counter, swaps, starts at 0. The cutting has reached the bottom of the array's left half, [4, 2], which is now a left list holding 4 and a right list holding 2."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-singles","state":{"arrays":[{"name":"left","values":[4],"current":0},{"name":"right","values":[2],"current":0},{"name":"merged","values":[]}],"swaps":0}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Count [4, 2, 3, 1] from single values up","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-singles","state":{"arrays":[{"name":"left","values":[4],"current":0},{"name":"right","values":[2],"current":0},{"name":"merged","values":[]}],"swaps":0}},{"id":"two-placed","state":{"arrays":[{"name":"left","values":[4],"current":0},{"name":"right","values":[2],"used":[0]},{"name":"merged","values":[2]}],"swaps":1}},{"id":"left-half-done","state":{"arrays":[{"name":"left","values":[4],"used":[0]},{"name":"right","values":[2],"used":[0]},{"name":"merged","values":[2,4]}],"swaps":1}},{"id":"halves-ready","state":{"arrays":[{"name":"left","values":[2,4],"current":0},{"name":"right","values":[1,3],"current":0},{"name":"merged","values":[]}],"swaps":2}},{"id":"one-placed","state":{"arrays":[{"name":"left","values":[2,4],"current":0},{"name":"right","values":[1,3],"used":[0],"current":1},{"name":"merged","values":[1]}],"swaps":4}},{"id":"two-placed-next","state":{"arrays":[{"name":"left","values":[2,4],"used":[0],"current":1},{"name":"right","values":[1,3],"used":[0],"current":1},{"name":"merged","values":[1,2]}],"swaps":4}},{"id":"all-merged","state":{"arrays":[{"name":"left","values":[2,4],"used":[0,1]},{"name":"right","values":[1,3],"used":[0,1]},{"name":"merged","values":[1,2,3,4]}],"swaps":5}}]},"beats":[{"id":"two-before-four","title":"2 is smaller than 4, so 2 goes into merged first. What is added to swaps?","options":[{"id":"adds-one","label":"1: 2 passes 4","rationale":"4 was ahead of 2 in the array and is larger, so that is one out-of-order pair.","isCorrect":true},{"id":"adds-zero","label":"0: taking the smaller value is free","rationale":"2 started behind 4. Moving it in front of 4 is the one swap this pair needs.","isCorrect":false},{"id":"adds-two","label":"2: one for each value","rationale":"Only one pair exists here, 4 before 2. Passing 4 is a single swap.","isCorrect":false}]},{"id":"leftover-four","title":"The right list is used up and 4 is still waiting. What does placing 4 add to swaps?","options":[{"id":"four-adds-one-larger","label":"1: 4 is larger than 2","rationale":"That pair was counted when 2 passed 4. Counting it again would report 2 swaps for [4, 2], which needs 1.","isCorrect":false},{"id":"four-adds-nothing","label":"Nothing: 4 passes no value","rationale":"4 goes onto the end of merged. Its only out-of-order pair, with 2, was counted when 2 went in.","isCorrect":true},{"id":"four-adds-one-placement","label":"1: every placement costs a swap","rationale":"A swap is counted only when a value moves ahead of a larger one. 4 moves ahead of nothing.","isCorrect":false}]},{"id":"right-half-same-steps","title":"The left half comes back as [2, 4], with 1 swap counted. The right half, [3, 1], goes through the same steps. What does it come back as?","options":[{"id":"sorted-and-counted","label":"[1, 3], and swaps rises to 2","rationale":"3 and 1 are cut apart, 1 goes into merged first and passes 3, then 3 follows. That is one more swap.","isCorrect":true},{"id":"sorted-not-counted","label":"[1, 3], and swaps stays at 1","rationale":"1 started behind 3 and ends ahead of it. That pass is a swap, the same as 2 passing 4.","isCorrect":false},{"id":"counted-not-sorted","label":"[3, 1], and swaps rises to 2","rationale":"The merge places the smaller value first, so the half comes back sorted as [1, 3].","isCorrect":false}]},{"id":"one-passes-both","title":"Both halves are sorted, and swaps holds their 2 inside pairs. Now they are merged, and 1 is smaller than the left front, 2. How many values on the left does 1 pass?","options":[{"id":"passes-front-only","label":"1: only the front value 2","rationale":"4 is behind 2 in a sorted list, so it is at least as large as 2 and therefore larger than 1. 1 passes it too.","isCorrect":false},{"id":"passes-both","label":"2: both 2 and 4","rationale":"The left list is sorted, so 4 sits behind 2 and is at least as large. A value smaller than 2 is smaller than 4 as well, so one comparison counted two pairs. On a longer sorted list it would count every value from the front to the end.","isCorrect":true},{"id":"needs-second-comparison","label":"Unknown until 1 is compared with 4","rationale":"The comparison with 2 already settles it. In a sorted list every value behind 2 is at least 2.","isCorrect":false}]},{"id":"two-goes-next","title":"The fronts are now 2 and 3. 2 is smaller and goes in. What does that add to swaps?","options":[{"id":"two-adds-nothing","label":"Nothing: 2 passes no value","rationale":"2 was already ahead of 3 in the array, and that pair is in order. A value taken from the left never moves ahead of anything.","isCorrect":true},{"id":"two-passes-three","label":"1: 2 passes 3","rationale":"2 was ahead of 3 before the merge and still is. Nothing changed places.","isCorrect":false},{"id":"two-was-passed","label":"1: 1 jumped ahead of 2","rationale":"That pair, 2 before 1, was counted when 1 went in and passed both left values.","isCorrect":false}]},{"id":"three-passes-four","title":"3 is the smaller front and goes in, then 4 follows as the last value. What is swaps at the end?","options":[{"id":"ends-at-six","label":"6: 3 passes the whole left list","rationale":"2 went into merged before 3 and stays ahead of it, which is the right order for that pair. Only values still waiting get passed.","isCorrect":false},{"id":"ends-at-four","label":"4: 3 was already in place","rationale":"4 was ahead of 3 in the array and is larger. Putting 3 first passes it, which is one more swap.","isCorrect":false},{"id":"ends-at-five","label":"5: 3 passes only 4","rationale":"2 has already left the left list, so 4 is the only value still waiting when 3 goes in, and 4 then adds nothing. swaps ends at 5, one for each out-of-order pair, and that is what the function returns.","isCorrect":true}]}]},{"id":"unsorted-halves-probe","kind":"case-probe","title":"Suppose the halves had not been sorted before the merge. How many values on the left is the right front, 3, smaller than?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"raw-halves","state":{"arrays":[{"name":"left","values":[4,2],"current":0},{"name":"right","values":[3,1],"current":0}]}}]},"options":[{"id":"both-left-values","label":"2: both 4 and 2","rationale":"That step relied on the left list being sorted. Here 2 sits behind 4 and is smaller than 3, so 2 before 3 is in order.","isCorrect":false},{"id":"only-four","label":"1: only 4","rationale":"4 is larger than 3, but 2 is smaller. Adding 2 here, as the merge would, counts a pair that was never out of order. Counting everything behind the front only works on sorted lists, which is why each piece is written back in sorted order before a longer piece merges it.","isCorrect":true},{"id":"no-left-values","label":"None","rationale":"4 is ahead of 3 and larger, so that pair is out of order.","isCorrect":false}]},{"id":"edge-case-intro","kind":"info","title":"That settles [4, 2, 3, 1]. Two more arrays come next.","workspacePanel":"visualizer","body":["[4, 2, 3, 2] has two equal values that meet during a merge. [1, 2, 3, 4] is already sorted."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-inputs","state":{"arrays":[{"name":"equal values","values":[4,2,3,2]},{"name":"already sorted","values":[1,2,3,4]}]}}]}},{"id":"duplicates-probe","kind":"case-probe","title":"In [4, 2, 3, 2], the last merge has a 2 at both fronts. Which one goes into merged, and what is added to swaps?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"equal-fronts","state":{"arrays":[{"name":"left","values":[2,4],"current":0},{"name":"right","values":[2,3],"current":0},{"name":"merged","values":[]}]}}]},"options":[{"id":"right-two-counted","label":"The right 2, adding 2","rationale":"That counts the right 2 as passing the left 2, and two equal values never need to swap. The merge would report 3 pairs across the cut where there are 2.","isCorrect":false},{"id":"left-two-free","label":"The left 2, adding nothing","rationale":"Equal values are already in order, so the left 2 goes first and nothing is counted. The right 2 stays at the front and passes 4 on the next step, adding 1.","isCorrect":true},{"id":"right-two-free","label":"The right 2, adding nothing","rationale":"The right 2 would go in without ever meeting 4, so the pair 4 before 2 is never counted. The merge would report 1 pair across the cut where there are 2.","isCorrect":false}]},{"id":"already-sorted-probe","kind":"case-probe","title":"In [1, 2, 3, 4], the last merge has placed both left values. What do 3 and 4 add when they follow?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"left-used-up","state":{"arrays":[{"name":"left","values":[1,2],"used":[0,1]},{"name":"right","values":[3,4],"current":0},{"name":"merged","values":[1,2]}],"swaps":0}}]},"options":[{"id":"nothing-waiting","label":"Nothing: no value on the left is still waiting","rationale":"A value from the right adds the number of left values still waiting, and here that number is 0. So a sorted array returns 0 with no special check, and so does a one-value array, whose first call is already on a one-value piece.","isCorrect":true},{"id":"left-size-each","label":"2 each: the size of the left list","rationale":"Only values still waiting are passed. 1 and 2 are already in merged, ahead of 3 and 4, where they belong.","isCorrect":false},{"id":"one-each","label":"1 each: every value from the right costs a swap","rationale":"A value from the right costs one swap for each larger value it moves ahead of. 3 and 4 move ahead of nothing.","isCorrect":false}]},{"id":"ready-to-code","kind":"info","title":"The plan is finished. Next, the function that runs it.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["The fewest swaps is the number of pairs with the larger value first, and the function counts them while it sorts.","It works on one piece of the array at a time, starting with the whole array. A piece with one value or none returns 0. A longer piece is cut at its middle, and each half is counted and sorted the same way.","Then the two sorted halves are merged by taking the smaller front value, the left one on a tie. Each time a value comes from the right, it adds the number of left values still waiting.","The merged order is written back over the piece, and the piece returns its halves' counts plus what its merge added."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"input-and-result","state":{"arrays":[{"name":"nums","values":[4,2,3,1]},{"name":"merged","values":[1,2,3,4]}],"swaps":5}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Sort `nums` by merging and return the count","workspacePanel":"code","checkpoints":[{"id":"merge-sort-helper","title":"Write the helper for one piece","description":"Write a helper that works on one piece of the array, given where the piece starts and ends. A piece with one value or none has no pairs inside it, so the helper returns 0 for it right away. For anything longer, find the middle position, where the piece will be cut.","commonMistakes":["Stopping only when the piece is empty, so a one-value piece keeps cutting itself forever","Returning the piece itself when the helper should return a count"],"hint":"A piece whose start has reached its end holds at most one value, and there is nothing in it to compare.","semanticSpec":{"intent":"Create the recursive interval-counting shell.","doneWhen":"The helper stops on collapsed intervals and splits by midpoint.","shouldFailWhen":"This step should fail if there is no recursive interval helper.","roles":["left bound","right bound","midpoint"],"mustProve":["Collapsed intervals return zero."],"mustNotAccept":["Flat nested-loop counting."],"equivalentVariants":["Use inclusive or half-open interval bounds if the base case is equivalent."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sequence-ordering","fact":"short_circuits_collapsed_interval_with_zero_return","scope":"base-case","readMode":"legacy-fact-query-v1"}]}},{"id":"recursive-calls","title":"Count inside each half","description":"Call the helper on the left half and on the right half of the piece, and start this piece's count from the sum of what the two calls return.","commonMistakes":["Calling the helper on one half only","Dropping what the two calls return, so only the pairs across the cut get counted"],"hint":"Each call does two jobs: it sorts its half and it reports the out-of-order pairs inside that half. Both reports belong in the total.","semanticSpec":{"intent":"Split the interval recursively and combine child counts.","doneWhen":"The helper calls itself on both midpoint halves.","shouldFailWhen":"This step should fail if either half is skipped.","roles":["recursive helper","left interval","right interval"],"mustProve":["Both midpoint subintervals are processed recursively."],"mustNotAccept":["Sorting only one side before merge."],"equivalentVariants":["Store child results separately or add them directly."]},"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-swaps","title":"Count the pairs across the cut","description":"While merging, compare the two front values. Whenever the right front is strictly smaller than the left front, add the number of left-half values that have not been placed yet.","commonMistakes":["Adding 1 each time a right-half value is placed, which misses the values behind the left front","Adding the full size of the left half, which also counts values that were already placed","Counting a tie as a pass, when two equal values never need to swap"],"hint":"The left half is sorted, so a right-half value that is smaller than the left front is smaller than everything from that front to the end of the left half.","semanticSpec":{"intent":"Update the accumulated swap count from merge comparisons.","doneWhen":"The accumulator increases when a right-half value must move before remaining left-half values.","shouldFailWhen":"This step should fail if the merge never updates the count.","roles":["swap count","left pointer","right pointer"],"mustProve":["The scalar accumulator is additively updated inside the merge logic."],"mustNotAccept":["Counting without using the merge boundary."],"equivalentVariants":["Use `mid - left + 1` or an equivalent remaining-left count."]},"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 and write the result back","description":"Build the sorted order by taking the smaller front value each time, with the left value first on a tie. When one half runs out, the rest of the other half follows. Then write the sorted order back over this piece of the array.","commonMistakes":["Counting without writing the sorted order back, which leaves an unsorted piece for the next merge","Stopping when one half runs out and losing the values still waiting in the other half"],"hint":"This piece is merged into a longer piece next, and the counting there is only right if this piece sits in the array in sorted order.","semanticSpec":{"intent":"Restore sorted interval order for parent merge levels.","doneWhen":"The code merges both halves, flushes remainders, and writes the buffer back.","shouldFailWhen":"This step should fail if the sorted interval is not written back.","roles":["left pointer","right pointer","temporary buffer"],"mustProve":["The merge writes a sorted buffer back into the source interval."],"mustNotAccept":["Counting without merging."],"equivalentVariants":["Use a temporary list or array."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sequence-ordering","fact":"merges_sorted_intervals_with_writeback","scope":"merge-arrays","readMode":"sequence-ordering-value-query-v1"}]}},{"id":"return-count","title":"Return the count for the whole array","description":"The helper returns the total for its piece: the counts from its two halves plus the pairs it found across the cut. The function returns what the helper reports for the piece that covers all of `nums`.","commonMistakes":["Returning the sorted array when the answer is a number","Returning only the pairs found in the last merge"],"hint":"The first call covers the array from its first position to its last.","semanticSpec":{"intent":"Return the terminal scalar accumulator.","doneWhen":"The method returns the accumulated count from the full array interval.","shouldFailWhen":"This step should fail if the final result is not the accumulated count.","roles":["swap count","full interval"],"mustProve":["The terminal accumulator is returned."],"mustNotAccept":["Returning the sorted array instead of the count."],"equivalentVariants":["Store the helper result in a variable before returning it."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_terminal_accumulator","scope":"return-result","readMode":"array-scan-value-query-v1"}]}}]},{"id":"complete","kind":"complete","title":"Neighbor swaps, counted by a merge sort","workspacePanel":"code","takeaways":[{"title":"The answer is a pair count","body":"A neighbor swap fixes at most one pair that has its larger value first. An unsorted array always has a neighboring pair to fix, so the fewest swaps equals the number of such pairs. They are called inversions."},{"title":"Sorted halves count pairs in bulk","body":"When a right-half value is smaller than the left front, it is smaller than every left-half value still waiting, so one comparison adds them all. A tie takes the left value and adds nothing."},{"title":"Every piece comes back sorted","body":"The bulk count is only right on sorted halves, so each merge writes its sorted order back into the array before a longer piece is merged from it. Cutting to single values and merging back up this way is merge sort."},{"title":"O(n log n) time, O(n) space","body":"The array can be halved about log n times, and the merges at any one level cover at most n values in total. So the time is O(n log n), where checking every pair is O(n^2). The merged list needs up to n extra slots, so the space is O(n)."}]}],"slidesOrigin":"authored"},"starterFunctionName":"minimumAdjacentSwapsToSort","tags":["Merge Sort","Inversions","Sorting"]}
