{"id":"number-of-pairs-satisfying-inequality","title":"Number of Pairs Satisfying Inequality","difficulty":"hard","patterns":["sorting-divide-conquer"],"primaryConcept":"sorting-divide-conquer","concepts":["sorting-divide-conquer"],"problemForm":"advanced","companies":["Google","Amazon","Meta","Microsoft"],"category":"searching-sorting","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"two-arrays","primaryParam":"nums1","secondaryParam":"nums2","sizeMetric":"total-length","sizes":[8,16,32,64],"valueRange":{"min":-50,"max":50},"secondaryParams":{"diff":{"strategy":"random-int","value":{"min":-20,"max":20}}}},"description":"You are given two integer arrays `nums1` and `nums2` of the same length, and an integer `diff`.\n\nReturn the number of index pairs `(i, j)` where `i < j` and:\n\n`nums1[i] - nums2[i] <= nums1[j] - nums2[j] + diff`\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":["numberOfPairs"],"case":"worst","enforcement":"hard","reason":"Each merge-sort level counts valid cross-half pairs and merges the interval in linear time."}],"examples":[{"input":"nums1 = [3,2,5], nums2 = [2,2,1], diff = 1","output":"3","explanation":"The transformed values are [1,0,4], and all three index pairs satisfy the inequality."},{"input":"nums1 = [3,-1], nums2 = [-2,2], diff = -1","output":"0","explanation":"The only transformed pair is 5 and -3, and 5 <= -3 + (-1) is false."}],"constraints":[{"id":"1-len-nums1-len-nums2-10-5","text":"1 <= len(nums1) == len(nums2) <= 10^5","check":[{"kind":"sizeRange","target":"nums1","measure":"arrayLength","min":1,"max":100000},{"kind":"sizeRange","target":"nums2","measure":"arrayLength","min":{"sizeOfInput":"nums1","measure":"arrayLength"},"max":{"sizeOfInput":"nums1","measure":"arrayLength"}}]},{"id":"10-9-nums1-i-nums2-i-10-9","text":"-10^9 <= nums1[i], nums2[i] <= 10^9","check":[{"kind":"valueRange","target":"nums1","selector":"arrayItems","min":-1000000000,"max":1000000000},{"kind":"valueRange","target":"nums2","selector":"arrayItems","min":-1000000000,"max":1000000000}]},{"id":"10-4-diff-10-4","text":"-10^4 <= diff <= 10^4","check":{"kind":"valueRange","target":"diff","selector":"value","min":-10000,"max":10000}},{"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 numberOfPairs(self, nums1: list[int], nums2: list[int], diff: int) -> int:\n        # Your code here\n        pass","functionName":"numberOfPairs","testCases":[{"id":"1","input":{"nums1":[3,2,5],"nums2":[2,2,1],"diff":1},"expected":3,"description":"Classic sample where every pair is valid."},{"id":"2","input":{"nums1":[3,-1],"nums2":[-2,2],"diff":-1},"expected":0,"description":"The only possible pair violates the inequality."},{"id":"3","input":{"nums1":[1,10,6,2],"nums2":[1,2,3,4],"diff":2},"expected":3,"description":"Only the first transformed value pairs with all later values."},{"id":"4","input":{"nums1":[4,4,4],"nums2":[1,1,1],"diff":0},"expected":3,"description":"Equal transformed values form every increasing index pair."},{"id":"5","input":{"nums1":[-5,-2,0],"nums2":[0,-3,-1],"diff":-2},"expected":2,"description":"Negative transformed values still use the same sorted cross-pair rule."},{"id":"6","input":{"nums1":[5,4,3,2],"nums2":[0,0,0,0],"diff":-3},"expected":0,"description":"A strict negative diff can eliminate all descending pairs."},{"id":"7","input":{"nums1":[1,2,3,4,5],"nums2":[0,0,0,0,0],"diff":0},"expected":10,"description":"An ascending transformed array makes every pair valid."},{"id":"hidden-1","input":{"nums1":[7],"nums2":[3],"diff":5},"expected":0,"description":"A single index cannot form a pair."},{"id":"hidden-2","input":{"nums1":[1000000000,-1000000000,1000000000],"nums2":[-1000000000,1000000000,0],"diff":10000},"expected":1,"description":"Large transformed values require safe arithmetic."},{"id":"hidden-3","input":{"nums1":[3,1,2,5],"nums2":[0,0,1,2],"diff":0},"expected":4,"description":"Mixed equal and larger transformed values exercise cross-half counting."},{"id":"topup-descending-no-pairs","input":{"nums1":[10,0,-10],"nums2":[0,0,0],"diff":0},"expected":0,"description":"A strictly descending transformed array leaves no valid increasing-index pairs."},{"id":"topup-equal-values-negative-diff","input":{"nums1":[0,0,0,0],"nums2":[0,0,0,0],"diff":-1},"expected":0,"description":"Equal transformed values fail when diff is negative."},{"id":"topup-positive-diff-partial","input":{"nums1":[5,1,3,2],"nums2":[0,0,0,0],"diff":2},"expected":4,"description":"A positive diff admits some, but not all, descending transformed pairs."},{"id":"topup-duplicates-with-small-margin","input":{"nums1":[3,1,2,1],"nums2":[0,0,0,0],"diff":1},"expected":4,"description":"Duplicate low values and a small diff exercise equality at the boundary."}],"hints":[{"level":1,"content":"Rewrite the inequality using `values[i] = nums1[i] - nums2[i]`."},{"level":2,"content":"After both halves are sorted, use one right pointer to skip values that are still too small for the current left value."},{"level":3,"content":"Count valid cross-half pairs before merging the two sorted halves back into the transformed array."}],"guidedFlow":{"version":2,"progressRevision":"number-of-pairs-satisfying-inequality-2026-11-20-halves-and-markers","approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"brute-force","name":"Check every pair","summary":"Transform once, then compare all i < j pairs directly.","decisionReason":"It makes one comparison per pair, n(n-1)/2 in all, and reuses no order, so each value re-scans the whole tail behind it.","complexity":{"time":"O(n^2)","space":"O(n)"},"tradeoffs":["Runs in O(n^2) time and uses O(n) space for the transformed array."],"isOptimal":false},{"id":"merge-sort-counting","name":"Transform then merge-sort count","summary":"Build the difference array, recursively sort intervals, count valid cross-half pairs with a forward pointer, then merge.","decisionReason":"Sorted halves let each level count its valid cross pairs in one linear sweep of a forward pointer, so the work is O(n log n) instead of re-scanning every pair.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Runs in O(n log n) time and uses O(n) space."],"isOptimal":true},{"id":"compressed-index-counts","name":"Compressed counts with ordered lookup","summary":"Scan transformed values left to right, coordinate-compress prior values, and query how many earlier values clear the inequality.","decisionReason":"A Fenwick or segment tree counts the same valid pairs in O(n log n) time. This flow uses merge order so counting and ordering happen in the same recursive structure without a compressed index map.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Runs in O(n log n) time and uses O(n) space, but needs extra indexed-count machinery and careful query bounds."],"isViable":true,"isOptimal":false}]},"codingCheckpoints":[{"id":"recursive-calls","title":"Build the values, then cut each piece in half","description":"Build the array with one number per position, nums1[k] - nums2[k]. Then write a helper that counts the pairs inside one piece of that array. A piece with one value counts 0. A longer piece is cut at its middle and starts from the counts of its two halves.","commonMistakes":["Counting inside only one of the two halves","Returning 1 for a piece that holds a single value","Cutting so that one half is empty, which never gets down to a single value"],"hint":"A single position cannot form a pair, so the smallest piece contributes 0.","semanticSpec":{"intent":"Set up midpoint interval recursion over the transformed array.","doneWhen":"The helper returns zero for collapsed intervals and recurses on both midpoint halves.","shouldFailWhen":"Only one half is processed or the base case returns a positive count.","roles":["lower bound","upper bound","midpoint","recursive count"],"mustProve":["The interval is split around a midpoint and both halves are recursively counted."],"mustNotAccept":["Flat nested-loop counting without recursive interval splitting."],"equivalentVariants":["Use inclusive interval bounds or equivalent start/end helper parameters."]},"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 middle","description":"Both halves come back sorted. Step through the left half, and keep one marker in the right half that moves past every value too small to pair with the current left value. Add the number of right values from the marker to the end.","commonMistakes":["Moving the marker back to the front of the right half for each left value, which repeats tests that already failed","Adding the values the marker passed, which are the ones that failed","Counting after the merge, when left and right values are mixed together"],"hint":"The marker stops on the first right value that passes, and every value after it passes too.","semanticSpec":{"intent":"Add valid cross-half pair counts into the accumulator.","doneWhen":"The helper additively updates the count while scanning the interval.","shouldFailWhen":"The cross-pair count is never added to the recursive total.","roles":["accumulator","left scan","right pointer"],"mustProve":["A running total is updated with a cross-half contribution."],"mustNotAccept":["Only returning the recursive halves without cross-pair accumulation."],"equivalentVariants":["Count valid suffixes of the right half or equivalently count skipped invalid values and subtract."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"additively_updates_accumulator","scope":"update-total","readMode":"array-scan-value-query-v1"}]}},{"id":"merge-arrays","title":"Merge the two sorted halves","description":"Build one ascending run by taking the smaller of the two front values each time, then copy over whatever one half still holds. Write the run back into the same positions of the array.","commonMistakes":["Building the merged run without writing it back, so larger pieces count across unsorted halves","Stopping when one half runs out and losing the rest of the other half"],"hint":"A larger piece counts across these same positions next, so they have to hold the sorted run.","semanticSpec":{"intent":"Maintain sorted intervals after each count.","doneWhen":"The code performs a sorted merge with tail flush and writes the buffer back.","shouldFailWhen":"The merge buffer is built but not copied into the active array.","roles":["left cursor","right cursor","merge buffer","writeback"],"mustProve":["Sorted interval merge writes back into the source sequence."],"mustNotAccept":["A temporary sorted array that is never used by parent calls."],"equivalentVariants":["Use a reusable buffer or a fresh temporary list for each merge interval."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sequence-ordering","fact":"merges_sorted_intervals_with_writeback","scope":"merge-arrays","readMode":"sequence-ordering-value-query-v1"}]}},{"id":"return-total","title":"Return the count for the whole array","description":"Have the helper return its count, and return the helper's result for the full array.","commonMistakes":["Returning the sorted array in place of the count","Returning only the pairs across the top-level middle and dropping what the halves counted"],"hint":"Each piece adds three numbers: the pairs inside its left half, inside its right half and across its middle.","semanticSpec":{"intent":"Return the terminal accumulator.","doneWhen":"The function returns the count accumulated by the merge-sort helper.","shouldFailWhen":"The returned value is not the computed pair total.","roles":["answer count"],"mustProve":["The terminal accumulator is returned."],"mustNotAccept":["Returning only the transformed or sorted array."],"equivalentVariants":["Store the helper result first or return the helper call directly."]},"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 of positions that pass a test","workspacePanel":"problem","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"inputs","state":{"arrays":[{"name":"nums1","values":[8,6,5,9,6,2,7,4]},{"name":"nums2","values":[1,4,2,0,2,3,1,3]}],"diff":2}}]},"body":["You get two lists of numbers of the same length, and one more number. At each position, subtract the bottom number from the top one.","A pair is an earlier position and a later one. It counts when the earlier position's result is at most the later position's result plus the extra number. Return how many pairs count."]},{"id":"check-one-pair","kind":"case-probe","title":"Do positions 0 and 1 make a pair that counts?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"positions-0-and-1","state":{"arrays":[{"name":"nums1","values":[8,6,5,9,6,2,7,4],"i":0,"j":1},{"name":"nums2","values":[1,4,2,0,2,3,1,3],"i":0,"j":1}],"diff":2}}]},"options":[{"id":"swapped-sides","label":"Yes: 6 - 4 <= 8 - 1 + 2 is true","rationale":"That puts the later position on the left. Position 0 is the earlier one, so its numbers form the left side.","isCorrect":false},{"id":"earlier-on-the-left","label":"No: 8 - 1 <= 6 - 4 + 2 is false","rationale":"The earlier position, 0, always goes on the left. The left side is 7 and the right side is 4, and 7 <= 4 does not hold.","isCorrect":true},{"id":"ignores-nums2","label":"Yes: 8 <= 6 + 2 is true","rationale":"That reads only nums1. Each side first subtracts the nums2 number at the same position.","isCorrect":false}]},{"id":"one-number-per-position","kind":"info","title":"Each position contributes one number","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"values-row","state":{"arrays":[{"name":"nums1","values":[8,6,5,9,6,2,7,4]},{"name":"nums2","values":[1,4,2,0,2,3,1,3]},{"name":"values","values":[7,2,3,9,4,-1,6,1]}],"diff":2}}]},"body":["The test reads position k only through nums1[k] - nums2[k]. Subtract once per position and keep the results in an array called values.","For an earlier position i and a later position j, the pair counts when values[i] <= values[j] + diff, where diff is the extra number."]},{"id":"brute-force","kind":"code-trace","title":"Test every pair","workspacePanel":"trace","body":["The direct way is to try each position against every position after it."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"values = [nums1[k] - nums2[k] for k in range(len(nums1))]\ncount = 0\nfor i in range(len(values)):\n    for j in range(i + 1, len(values)):\n        if values[i] <= values[j] + diff:\n            count += 1\nreturn count","steps":[{"id":"transform","title":"One number per position","codeLine":1,"summary":"The highlighted code builds values. The two input arrays are not read again.","state":{"nums":[7,2,3,9,4,-1,6,1],"labels":{"nums":"values"},"diff":2}},{"id":"first-test","title":"7 against 2","codeLine":5,"summary":"7 <= 2 + 2 is false, so positions 0 and 1 add nothing to count.","state":{"nums":[7,2,3,9,4,-1,6,1],"labels":{"nums":"values"},"i":0,"j":1,"count":0,"diff":2}},{"id":"first-pass","title":"7 against 9","codeLine":6,"summary":"3 fails the same way. 9 passes, since 7 <= 9 + 2, and count becomes 1.","state":{"nums":[7,2,3,9,4,-1,6,1],"labels":{"nums":"values"},"i":0,"j":3,"count":1,"diff":2}},{"id":"position-0-done","title":"Seven tests for position 0","codeLine":4,"summary":"4, -1 and 1 fail, and 6 passes. Of the seven later values, 9 and 6 pair with 7.","state":{"nums":[7,2,3,9,4,-1,6,1],"labels":{"nums":"values"},"i":0,"j":7,"count":2,"diff":2}},{"id":"position-1-starts-over","title":"Position 1 starts over","codeLine":3,"summary":"2 is tested against each of the six values after it, one at a time.","state":{"nums":[7,2,3,9,4,-1,6,1],"labels":{"nums":"values"},"i":1,"j":2,"count":2,"diff":2}},{"id":"all-tested","title":"28 tests, 14 pairs","codeLine":7,"summary":"Position 0 took 7 tests, position 1 took 6, and so on down to 1.","state":{"nums":[7,2,3,9,4,-1,6,1],"labels":{"nums":"values"},"count":14,"diff":2}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const values = Array.from({ length: nums1.length }, (_, index) => index).map((k) => (nums1[k] - nums2[k]));\nlet count = 0;\nfor (let i = 0; i < values.length; i++) {\n    for (let j = (i + 1); j < values.length; j++) {\n        if (values[i] <= (values[j] + diff)) {\n            count++;\n        }\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const values = Array.from({ length: nums1.length }, (_, index) => index).map((k) => (nums1[k] - nums2[k]));\nlet count = 0;\nfor (let i = 0; i < values.length; i++) {\n    for (let j = (i + 1); j < values.length; j++) {\n        if (values[i] <= (values[j] + diff)) {\n            count++;\n        }\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> values = new ArrayList<>();\nfor (int k = 0; k < nums1.size(); k++) {\n    values.add((nums1.get(k) - nums2.get(k)));\n}\nint count = 0;\nfor (int i = 0; i < values.size(); i++) {\n    for (int j = (i + 1); j < values.size(); j++) {\n        if (values.get(i) <= (values.get(j) + diff)) {\n            count++;\n        }\n    }\n}\nreturn count;","lineMap":{"1":1,"2":5,"3":6,"4":7,"5":8,"6":9,"7":13},"statementBundles":{"1":{"startLine":1,"endLine":4},"6":{"startLine":9,"endLine":12}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> values = Enumerable.Range(0, nums1.Count).Select(k => nums1[k] - nums2[k]).ToList();\nint count = 0;\nfor (int i = 0; i < values.Count; i++) {\n    for (int j = i + 1; j < values.Count; j++) {\n        if (values[i] <= values[j] + diff) {\n            count++;\n        }\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> values;\nfor (int k = 0; k < nums1.size(); k++) {\n    values.push_back((nums1[k] - nums2[k]));\n}\nint count = 0;\nfor (int i = 0; i < values.size(); i++) {\n    for (int j = (i + 1); j < values.size(); j++) {\n        if (values[i] <= (values[j] + diff)) {\n            count++;\n        }\n    }\n}\nreturn count;","lineMap":{"1":1,"2":5,"3":6,"4":7,"5":8,"6":9,"7":13},"statementBundles":{"1":{"startLine":1,"endLine":4},"6":{"startLine":9,"endLine":12}}}}}},{"id":"waste-probe","kind":"case-probe","title":"Eight positions took 28 tests, and the arrays can hold 100,000 positions. About how many tests is that?","workspacePanel":"trace","options":[{"id":"one-per-position","label":"About 100,000","rationale":"That would be one test per position. Position 0 alone is tested against 99,999 later values.","isCorrect":false},{"id":"two-million","label":"About 2 million","rationale":"The first 20 positions use up about 2 million tests, and 99,980 positions are still to come.","isCorrect":false},{"id":"five-billion","label":"About 5 billion","rationale":"99,999 + 99,998 + ... + 1 comes to 4,999,950,000.","isCorrect":true}]},{"id":"cross-count-discovery","kind":"case-probe","title":"Suppose the seven later values were sorted. Which of them pair with 7?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"later-values-sorted","state":{"arrays":[{"name":"values","values":[7,2,3,9,4,-1,6,1],"i":0},{"name":"later values, sorted","values":[-1,1,2,3,4,6,9]}],"diff":2}}]},"options":[{"id":"only-nine","label":"Only 9, the one value above 7","rationale":"6 passes too: 7 <= 6 + 2. The later value may be smaller by up to diff.","isCorrect":false},{"id":"last-two","label":"6 and 9, the last two","rationale":"7 <= x + 2 needs x to be at least 5. 6 is the first value that large, and everything after it is larger still. In sorted order the values that pass sit together at the end, so finding where they start gives the count without a test per value.","isCorrect":true},{"id":"needs-every-test","label":"It takes all seven tests to know","rationale":"The order settles most of them. 4 fails, so everything before 4 fails, and 6 passes, so everything after 6 passes.","isCorrect":false}]},{"id":"sort-everything","kind":"case-probe","title":"This time sort all eight values first, then count the pairs in the sorted array. What does the count come to?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-sorted","state":{"arrays":[{"name":"values","values":[7,2,3,9,4,-1,6,1]},{"name":"values, sorted","values":[-1,1,2,3,4,6,7,9]}],"diff":2}}]},"options":[{"id":"same-count","label":"14, the same as before","rationale":"Sorting changed which value comes first. 7 sat before 2 and failed, and in sorted order 2 sits before 7 and passes.","isCorrect":false},{"id":"every-pair","label":"28, every pair there is","rationale":"In ascending order no value is larger than one after it, and diff is 2, so x <= y + 2 holds for all 28 pairs. A full sort moves values past each other, so it loses which value came first.","isCorrect":true},{"id":"fewer-pairs","label":"Fewer than 14","rationale":"Nothing fails in sorted order, because the earlier value of each pair is now the smaller one.","isCorrect":false}]},{"id":"split-in-half","kind":"case-probe","title":"Now sort each half on its own instead. In a pair with one value from each half, which value sat earlier in the original array?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"halves-sorted","state":{"arrays":[{"name":"values","values":[7,2,3,9,4,-1,6,1]},{"name":"left half","values":[2,3,7,9]},{"name":"right half","values":[-1,1,4,6]}],"diff":2}}]},"options":[{"id":"always-left","label":"The one from the left half, every time","rationale":"Sorting a half moves values only among positions 0 to 3, or only among positions 4 to 7. Nothing crosses the middle, so these 16 pairs can be counted in sorted order, the way the values that pair with 7 were.","isCorrect":true},{"id":"smaller-one","label":"The smaller of the two","rationale":"Size and position are unrelated. 9 is the largest value, and it sat at position 3, ahead of the whole right half.","isCorrect":false},{"id":"depends-on-sort","label":"It depends on where the sort put them","rationale":"The sort can reorder 7, 2, 3 and 9 among themselves, but all four stay ahead of position 4.","isCorrect":false}]},{"id":"pairs-inside-a-half","kind":"info","title":"Pairs inside a half are the same problem on a shorter array","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-values","title":"Single values","summary":"One value holds no pair, so a piece this small counts 0.","state":{"arrays":[{"name":"left half","values":[7,2,3,9]},{"name":"right half","values":[4,-1,6,1]}],"count":0,"diff":2}},{"id":"pieces-of-two","title":"Pieces of two","summary":"Each has one pair to test, and only 3 before 9 passes: 3 <= 9 + 2. Every piece is then put in ascending order.","state":{"arrays":[{"name":"left half","values":[2,7,3,9]},{"name":"right half","values":[-1,4,1,6]}],"count":1,"diff":2}},{"id":"pieces-of-four","title":"Pieces of four","summary":"[2, 7] against [3, 9] finds 3 pairs, and [-1, 4] against [1, 6] finds 3 more. Both pieces are put in order, with 7 pairs counted inside them.","state":{"arrays":[{"name":"left half","values":[2,3,7,9]},{"name":"right half","values":[-1,1,4,6]}],"count":7,"diff":2}}]},"body":["That leaves the pairs inside one half. The left half holds four values with pairs of their own. It is cut in the middle the way the full array was, and so is each smaller piece, down to single values."]},{"id":"dry-run-setup","kind":"info","title":"Two markers count the pairs across the middle","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"markers-at-the-front","state":{"arrays":[{"name":"left half","values":[2,3,7,9],"i":0},{"name":"right half","values":[-1,1,4,6],"j":0}],"count":7,"diff":2}}]},"body":["The marker i steps through the sorted left half. For the value under i, the marker j moves right past every value that fails the test, and stops on the first one that passes or runs off the end.","The count starts at 7, the pairs already found inside the two halves."]},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Count across the middle","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"before-2","state":{"arrays":[{"name":"left half","values":[2,3,7,9],"i":0},{"name":"right half","values":[-1,1,4,6],"j":0}],"count":7,"diff":2}},{"id":"after-2","state":{"arrays":[{"name":"left half","values":[2,3,7,9],"i":0},{"name":"right half","values":[-1,1,4,6],"used":[0],"j":1}],"count":10,"diff":2}},{"id":"i-on-3","state":{"arrays":[{"name":"left half","values":[2,3,7,9],"i":1},{"name":"right half","values":[-1,1,4,6],"used":[0],"j":1}],"count":10,"diff":2}},{"id":"after-3","state":{"arrays":[{"name":"left half","values":[2,3,7,9],"i":1},{"name":"right half","values":[-1,1,4,6],"used":[0],"j":1}],"count":13,"diff":2}},{"id":"after-7","state":{"arrays":[{"name":"left half","values":[2,3,7,9],"i":2},{"name":"right half","values":[-1,1,4,6],"used":[0,1,2],"j":3}],"count":14,"diff":2}},{"id":"after-9","state":{"arrays":[{"name":"left half","values":[2,3,7,9],"i":3},{"name":"right half","values":[-1,1,4,6],"used":[0,1,2,3]}],"count":14,"diff":2}}]},"beats":[{"id":"partners-of-2","title":"Which right values pair with 2?","options":[{"id":"only-larger","label":"Only 4 and 6","rationale":"1 passes as well: 2 <= 1 + 2. A right value may be smaller than the left one by up to diff.","isCorrect":false},{"id":"one-four-six","label":"1, 4 and 6","rationale":"2 <= -1 + 2 is false, so j moves past -1. 2 <= 1 + 2 holds, so j stops on 1, and 4 and 6 are larger still. Three values sit from j to the end, so count goes from 7 to 10.","isCorrect":true},{"id":"all-four","label":"All four","rationale":"Being in the right half only settles which value came first. The test still has to hold, and 2 <= -1 + 2 is false.","isCorrect":false}]},{"id":"no-going-back","title":"i steps from 2 to 3. Does j have to go back and test -1 again?","options":[{"id":"never-compared","label":"Yes: 3 has never been compared with -1","rationale":"It does not need to be. 2 <= -1 + 2 already failed, and 3 only makes the left side bigger.","isCorrect":false},{"id":"fresh-start","label":"Yes: every left value starts from the front","rationale":"That repeats a test whose result is known. The left half is sorted, so each new left value is at least as hard to pair with.","isCorrect":false},{"id":"still-too-small","label":"No: -1 was too small for 2, and 3 is larger","rationale":"A larger left value needs right values at least as large as before. Whatever failed for 2 fails for 3, so j only ever moves forward.","isCorrect":true}]},{"id":"equal-is-enough","title":"j is on 1. What does 3 add to count?","options":[{"id":"stays-on-1","label":"3, because j stays on 1","rationale":"3 <= 1 + 2 holds with both sides equal, and equal is enough. 1, 4 and 6 count again.","isCorrect":true},{"id":"moves-to-4","label":"2, because j moves on to 4","rationale":"That would need 3 <= 1 + 2 to fail. Both sides are 3, and the test allows them to be equal.","isCorrect":false},{"id":"only-under-j","label":"1, because only the value under j counts","rationale":"4 and 6 sit after j and are larger than 1, so they pass along with it.","isCorrect":false}]},{"id":"two-skipped","title":"i steps from 3 to 7. Where does j stop?","options":[{"id":"stops-on-4","label":"On 4","rationale":"7 <= 4 + 2 is 7 <= 6, which is false, so j moves past 4.","isCorrect":false},{"id":"past-the-end","label":"Past the end of the right half","rationale":"6 still passes: 7 <= 6 + 2. diff lets 7 pair with a value below it.","isCorrect":false},{"id":"stops-on-6","label":"On 6","rationale":"7 <= 1 + 2 and 7 <= 4 + 2 are both false, so j moves past 1 and 4. 7 <= 6 + 2 holds, so j stops on 6, and 7 adds 1 to make count 14.","isCorrect":true}]},{"id":"nothing-left","title":"i steps from 7 to 9. What does 9 add to count?","options":[{"id":"adds-nothing","label":"0, because j moves past 6 and nothing is left","rationale":"9 <= 6 + 2 is false, so j leaves the right half. With no values from j to the end, 9 has nothing to pair with. The count ends at 14, the same total that testing all 28 pairs gave.","isCorrect":true},{"id":"stays-on-last","label":"1, because j stays on the last value","rationale":"j stays only where the test holds, and 9 <= 6 + 2 is false.","isCorrect":false},{"id":"counts-passed","label":"4, because j has passed all four","rationale":"The values j passed are the ones that failed. The count comes from j to the end, and nothing is there.","isCorrect":false}]}]},{"id":"merge-halves","kind":"dry-run","source":"trace-example","title":"Merge the two sorted halves","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"nothing-merged","state":{"arrays":[{"name":"left half","values":[2,3,7,9],"i":0,"labels":{"i":"front"}},{"name":"right half","values":[-1,1,4,6],"j":0,"labels":{"j":"front"}},{"name":"merged","values":[]}]}},{"id":"first-written","state":{"arrays":[{"name":"left half","values":[2,3,7,9],"i":0,"labels":{"i":"front"}},{"name":"right half","values":[-1,1,4,6],"j":1,"labels":{"j":"front"},"used":[0]},{"name":"merged","values":[-1]}]}},{"id":"four-written","state":{"arrays":[{"name":"left half","values":[2,3,7,9],"i":2,"labels":{"i":"front"},"used":[0,1]},{"name":"right half","values":[-1,1,4,6],"j":2,"labels":{"j":"front"},"used":[0,1]},{"name":"merged","values":[-1,1,2,3]}]}},{"id":"written-back","state":{"nums":[-1,1,2,3,4,6,7,9],"labels":{"nums":"values"}}}]},"beats":[{"id":"first-written","title":"Each piece ends by merging its two sorted halves into one ascending run. Which value is written first?","options":[{"id":"left-front","label":"2, the front of the left half","rationale":"-1 would then land after 2, and the run would not ascend.","isCorrect":false},{"id":"smaller-front","label":"-1, the smaller of the two front values","rationale":"Each half is sorted, so its front value is its smallest. The smallest of all eight is the smaller of 2 and -1. Once -1 is written, the right half's front moves along to 1.","isCorrect":true},{"id":"either-front","label":"Either front value","rationale":"Keeping each half in its own order is not enough. Writing 2 before -1 puts a larger value ahead of a smaller one.","isCorrect":false}]},{"id":"next-three","title":"The fronts are now 2 and 1. Which three values are written next?","options":[{"id":"from-the-left","label":"2, 3, 7","rationale":"That keeps taking from the left half. 1 is smaller than 2, so it has to be written first.","isCorrect":false},{"id":"alternating","label":"1, 2, 3","rationale":"1 is smaller than 2. Then the fronts are 2 and 4, and after that 3 and 4.","isCorrect":true},{"id":"from-the-right","label":"1, 4, 6","rationale":"1 is right, but then the fronts are 2 and 4, and 2 is the smaller.","isCorrect":false}]},{"id":"leftover-values","title":"4 and 6 are written next, and the right half is used up. What happens to 7 and 9?","options":[{"id":"copied-over","label":"They are copied to the end of the run","rationale":"Nothing is left to compare them with, and they are already in order and larger than everything written so far. The finished run is then written back over the same positions of values, so the next larger piece finds its halves sorted.","isCorrect":true},{"id":"dropped","label":"They are left out, because one half has run out","rationale":"The run would then hold six of the eight values. Every value has to come back.","isCorrect":false},{"id":"go-first","label":"They move to the front of the run","rationale":"The run is ordered by value, and 7 and 9 are the two largest.","isCorrect":false}]}]},{"id":"level-cost","kind":"case-probe","title":"Now scale up to 100,000 values, 50,000 in each half. About how many steps do this count and this merge take?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"markers-at-the-end","state":{"arrays":[{"name":"left half","values":[2,3,7,9],"i":3},{"name":"right half","values":[-1,1,4,6],"used":[0,1,2,3]}],"count":14,"diff":2}}]},"options":[{"id":"every-cross-pair","label":"About 2.5 billion","rationale":"That is 50,000 x 50,000, one test for every pair across the middle. j made those tests unnecessary: one stop on 1 counted 1, 4 and 6 for 2.","isCorrect":false},{"id":"left-half-only","label":"About 50,000","rationale":"That covers i alone. j crosses the right half as well, and the merge writes all 100,000 values.","isCorrect":false},{"id":"few-passes","label":"About 300,000","rationale":"i crosses the left half once and j never moves back, so the two markers take at most 100,000 steps together. The merge writes each of the 100,000 values twice: into the run, and back into values. No round of halving costs more than this, and there are 17 rounds, so the whole count is a few million steps against 5 billion tests.","isCorrect":true}]},{"id":"edge-case-intro","kind":"info","title":"The count came out right on this example. Next, a negative diff and a single position.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"example-halves","state":{"arrays":[{"name":"left half","values":[2,3,7,9]},{"name":"right half","values":[-1,1,4,6]}],"diff":2}}]},"body":["diff can be below zero, and each array can hold just one number. Does the same function handle both without a rule of its own?"]},{"id":"negative-diff-probe","kind":"case-probe","title":"First, the same halves with diff = -2. Where does j stop for 2?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"negative-diff","state":{"arrays":[{"name":"left half","values":[2,3,7,9],"i":0},{"name":"right half","values":[-1,1,4,6],"j":0}],"diff":-2}}]},"options":[{"id":"same-as-before","label":"On 1, where it stopped before","rationale":"The test for 1 is now 2 <= 1 + (-2), which is false.","isCorrect":false},{"id":"on-four","label":"On 4","rationale":"2 <= -1 + (-2) and 2 <= 1 + (-2) are false, and 2 <= 4 + (-2) holds with both sides equal to 2. Nothing new is needed: the same test sends j further, and 2 adds 2 pairs where it added 3.","isCorrect":true},{"id":"nowhere","label":"Nowhere, because no pair can pass","rationale":"A negative diff only asks for more. 4 and 6 are far enough above 2 to pass.","isCorrect":false}]},{"id":"single-position-probe","kind":"case-probe","title":"Last, each array holds a single number. What does the function return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"one-position","state":{"arrays":[{"name":"nums1","values":[7]},{"name":"nums2","values":[3]},{"name":"values","values":[4]}],"diff":5}}]},"options":[{"id":"zero-from-the-smallest-piece","label":"0, from the rule for a piece with one value","rationale":"The whole array is already a piece with one value. A pair needs two positions, so it counts 0.","isCorrect":true},{"id":"pairs-with-itself","label":"1, because 4 <= 4 + 5 holds","rationale":"That tests position 0 against itself. A pair is an earlier position and a later one.","isCorrect":false},{"id":"needs-its-own-check","label":"It needs a check of its own before any cutting","rationale":"The check is already there. Every piece with one value returns 0, and here that piece is the whole array.","isCorrect":false}]},{"id":"ready-to-code","kind":"info","title":"Pairs inside each half, plus pairs across the middle","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"inputs-and-values","state":{"arrays":[{"name":"nums1","values":[8,6,5,9,6,2,7,4]},{"name":"nums2","values":[1,4,2,0,2,3,1,3]},{"name":"values","values":[7,2,3,9,4,-1,6,1]}],"diff":2}}]},"body":["The function first turns the two arrays into one, with one number per position. A helper counts the pairs in a piece of that array. A piece with one value counts 0. A longer piece is cut in the middle, and each half counts its own pairs and comes back sorted.","Then one forward marker counts the pairs across the middle, and the two halves are merged into one ascending run, written back in place.","The helper returns the pairs inside the left half, inside the right half and across the middle, added together. The function returns that total for the whole array."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Count the pairs while sorting","workspacePanel":"code"},{"id":"complete","kind":"complete","title":"Merge sort, with a count before each merge","workspacePanel":"code","takeaways":[{"title":"One number per position","body":"The test only uses nums1[k] - nums2[k], so the two arrays reduce to one, and a pair counts when values[i] <= values[j] + diff."},{"title":"Sort only where the earlier position is known","body":"A full sort loses which value came first, but sorting each half separately cannot move a left-half value behind a right-half one."},{"title":"One marker counts for a whole half","body":"In the sorted right half every value from j to the end passes, and j never moves back because the left values never get smaller."},{"title":"Time: O(n log n)","body":"The pieces made in one round of halving hold each value once between them, so counting and merging them takes O(n) work in total. An array of n values can be halved about log n times: 17 times for 100,000."},{"title":"Space: O(n)","body":"The values array and the run that each merge fills hold at most n numbers each."}]}],"slidesOrigin":"authored"}}
