{"id":"minimum-number-of-steps-to-make-two-strings-anagram-ii","title":"Minimum Number of Steps to Make Two Strings Anagram II","difficulty":"medium","patterns":["hash-map"],"primaryConcept":"hash-map-grouping","concepts":["hash-map-grouping"],"problemForm":"core","companies":["Amazon","Google","Meta"],"category":"hash-tables","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"two-strings","primaryParam":"s","secondaryParam":"t","sizeMetric":"total-length","sizes":[8,16,32,64]},"description":"You are given two strings `s` and `t`. In one step, you may append any lowercase English letter to either string.\n\nReturn the minimum number of steps needed to make `s` and `t` anagrams of each other.","examples":[{"input":"s = \"leetcode\", t = \"coats\"","output":"7","explanation":"The unmatched letters across the two frequency profiles require seven appended characters."},{"input":"s = \"night\", t = \"thing\"","output":"0","explanation":"The strings already have the same character counts."},{"input":"s = \"bab\", t = \"aba\"","output":"2","explanation":"One extra b is needed on t and one extra a is needed on s."}],"constraints":[{"id":"1-len-s-len-t-2-10-5","text":"1 <= len(s), len(t) <= 2 * 10^5","check":[{"kind":"sizeRange","target":"s","measure":"stringLength","min":1,"max":200000},{"kind":"sizeRange","target":"t","measure":"stringLength","min":1,"max":200000}]},{"id":"s-and-t-consist-of-lowercase-english-letters","text":"s and t consist of lowercase English letters.","check":[{"kind":"domain","target":"s","selector":"stringChars","allowed":["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]},{"kind":"domain","target":"t","selector":"stringChars","allowed":["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]}]}],"starterCode":"class Solution:\n    def minSteps(self, s: str, t: str) -> int:\n        # Your code here\n        pass","functionName":"minSteps","testCases":[{"id":"1","input":{"s":"leetcode","t":"coats"},"expected":7,"description":"Prompt example with several unmatched letters."},{"id":"2","input":{"s":"night","t":"thing"},"expected":0,"description":"Already anagrams."},{"id":"3","input":{"s":"bab","t":"aba"},"expected":2,"description":"One surplus on each side."},{"id":"4","input":{"s":"abc","t":"def"},"expected":6,"description":"No shared letters."},{"id":"5","input":{"s":"aaa","t":"aaaa"},"expected":1,"description":"One extra copy is needed."},{"id":"6","input":{"s":"xxyyzz","t":"xzz"},"expected":3,"description":"Only the unmatched x and y counts matter."},{"id":"h1","input":{"s":"a","t":"b"},"expected":2,"description":"Single different letters."},{"id":"h2","input":{"s":"ab","t":"ab"},"expected":0,"description":"Small identical counts."},{"id":"h3","input":{"s":"anagram","t":"mangaar"},"expected":0,"description":"Same counts in a different order."},{"id":"h4","input":{"s":"abcabc","t":"ab"},"expected":4,"description":"The first string has extra a, b, and c copies."},{"id":"topup-disjoint-strings","input":{"s":"leetcode","t":"practice"},"expected":10,"description":"Disjoint strings require replacing every character count."},{"id":"topup-overlapping-counts","input":{"s":"aabbcc","t":"abccdd"},"expected":4,"description":"Shared and extra counts both contribute to the total steps."}],"hints":[{"level":1,"content":"Anagrams are determined by character counts, not by order.","revealPattern":false},{"level":2,"content":"Track the signed difference between the two strings for each character.","revealPattern":true},{"level":3,"content":"Add the absolute value of every signed count difference. Each unmatched character requires one appended character.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose cost matches scanning each string a constant number of times.","approaches":[{"id":"nested-match","name":"Match each character by searching","summary":"For every character in one string, scan the other to cross off a matching copy, then count what is left unmatched.","decisionReason":"Every character re-scans the other string, so the work grows with the product of the two lengths.","complexity":{"time":"O(n * m)","space":"O(n + m)"},"tradeoffs":["Re-scans the other string once per character."],"isOptimal":false},{"id":"signed-frequency-balance","name":"Signed frequency balance","summary":"Keep one per-letter count that the two strings push in opposite directions, then total the leftover gaps in a single pass.","decisionReason":"Each string is touched once and the leftover gaps are summed once, so the cost is the sum of the two lengths.","complexity":{"time":"O(n + m)","space":"O(1)"},"tradeoffs":["Holds one small per-letter tally and never re-scans either string."],"isOptimal":true},{"id":"sort-and-compare","name":"Sort both strings","summary":"Sort both strings and walk the two sorted sequences together, counting positions that fail to line up.","decisionReason":"Sorting costs more than a single tally and the order it produces is never needed.","complexity":{"time":"O(n log n + m log m)","space":"O(n + m)"},"tradeoffs":["Pays a sort the counts never require."],"isOptimal":false}]},"codingCheckpoints":[{"id":"init-balance-map","title":"Create the balance map","description":"Set up keyed state that will hold a signed count gap for each letter.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"initializes_keyed_state","scope":"init-frequency-map","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Using a single scalar total instead of a count per letter","Rebuilding the map inside the character loops"],"hint":"The map holds a signed gap per letter, keyed by the character.","semanticSpec":{"intent":"Initialize keyed count state before any character is tallied.","doneWhen":"A map-like count state exists before either string is scanned.","shouldFailWhen":"This step should fail if no keyed state is initialized.","roles":["balance map"],"mustProve":["The solution initializes keyed state."],"mustNotAccept":["A single scalar total that cannot separate letters."]}},{"id":"record-signed-counts","title":"Raise for s, lower for t","description":"Walk both strings, raising a letter's count for each character of the first string and lowering it for each character of the second.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"counts_items_by_key","scope":"count-frequencies","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Tallying only one string","Raising the count for both strings and erasing the gap"],"hint":"One string raises a letter's count, the other lowers it.","semanticSpec":{"intent":"Accumulate a signed gap per letter across both strings.","doneWhen":"Each letter of the two strings adjusts its own count in opposite directions.","shouldFailWhen":"This step should fail if both strings adjust the count the same way.","roles":["current character","balance map"],"mustProve":["The keyed state counts items by key."],"mustNotAccept":["A write that pushes both strings the same direction and loses the gap."]}},{"id":"init-total","title":"Start the step total at zero","description":"Create an accumulator for the number of appends, beginning before any gap is added.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_zero_accumulator","scope":"init-total","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Starting from one instead of zero","Returning the map itself as the total"],"hint":"No gaps have been added yet, so the total begins at zero.","semanticSpec":{"intent":"Initialize the step accumulator before summing gaps.","doneWhen":"A numeric total is set to zero before the gap loop.","shouldFailWhen":"This step should fail if the accumulator does not start at zero.","roles":["step total"],"mustProve":["The solution initializes a zero accumulator."],"mustNotAccept":["An accumulator seeded with a nonzero value."]}},{"id":"scan-differences","title":"Walk every leftover gap","description":"Loop over the final per-letter gaps stored in the map.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence","scope":"loop-through-nums","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Returning after a single letter","Re-scanning a string instead of the computed gaps"],"hint":"Iterate over `balance.values()` after both strings have been tallied.","semanticSpec":{"intent":"Scan each stored per-letter gap.","doneWhen":"The solution loops across the gap values to total them.","shouldFailWhen":"This step should fail if no sequence of gaps is scanned.","roles":["balance map","current gap"],"mustProve":["The traversal reads a sequence of values."],"mustNotAccept":["A fixed single-gap read."]}},{"id":"add-absolute-differences","title":"Add each gap's magnitude","description":"Add the absolute value of every signed gap to the running total.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"additively_updates_accumulator","scope":"update-total","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Adding signed gaps directly, letting a surplus cancel a shortfall","Counting only the positive gaps"],"hint":"A gap of plus one and a gap of minus one each cost one append, so add magnitudes.","semanticSpec":{"intent":"Add the magnitude of each gap to the accumulator.","doneWhen":"Each gap raises the total by its absolute value.","shouldFailWhen":"This step should fail if signed gaps are added so opposites cancel.","roles":["current gap","step total"],"mustProve":["The accumulator is updated additively."],"mustNotAccept":["A sum of signed gaps that lets a surplus cancel a shortfall."]}},{"id":"return-total","title":"Return the step total","description":"Return the accumulator once every gap has been added.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_terminal_accumulator","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Returning the balance map","Returning before every gap is summed"],"hint":"Return the total after the loop over gaps finishes.","semanticSpec":{"intent":"Return the accumulated step total.","doneWhen":"The function returns the total after the gap loop completes.","shouldFailWhen":"This step should fail if it returns before all gaps are summed.","roles":["step total","return value"],"mustProve":["The solution returns the terminal accumulator."],"mustNotAccept":["Returning the map or a partial total."]}}],"slides":[{"id":"opener","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Append letters until the counts match","workspacePanel":"problem","body":["You get two strings, s and t. One step appends any lowercase letter to either string, and you want the fewest steps that make the two strings anagrams, meaning they hold the same letters with the same counts.","The direct way is to match each character against the other string and count what is left over. Watch it work, and watch what it costs."]},{"id":"brute-force","chapter":"The problem","kind":"code-trace","eyebrow":"The direct way","title":"Cross off matches by searching","summary":"Matching each character against the other string finds every unmatched letter, and the count is right, but watch how much of t each character of s re-reads.","workspacePanel":"trace","body":["For each character of s, scan t for an unused matching copy and cross it off. Whatever stays unmatched in s, plus whatever stays unmatched in t, is the answer."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"used = [False, False, False]\nunmatched = 0\nfor ch in s:\n    found = False\n    for k in range(3):\n        if t[k] == ch and used[k] == False:\n            used[k] = True\n            found = True\n    if found == False:\n        unmatched += 1\nleftover = 0\nfor u in used:\n    if u == False:\n        leftover += 1\nreturn unmatched + leftover","steps":[{"id":"first-b","title":"First b searches t","codeLine":6,"summary":"s = \"bab\", t = \"aba\". The first character b scans t for a b and crosses off the one at index 1.","state":{"s":"aba","i":1,"ch":"b","labels":{"s":"t","i":"k"}}},{"id":"first-a-restart","title":"The a restarts the search","codeLine":5,"summary":"The next character a begins another full scan of t from the front. The string is re-read from scratch.","state":{"s":"aba","i":0,"ch":"a","labels":{"s":"t","i":"k"}}},{"id":"first-a-found","title":"It lands on the first a","codeLine":6,"summary":"The unused a at index 0 is found and crossed off. Two characters of s, two full scans of t.","state":{"s":"aba","i":0,"ch":"a","labels":{"s":"t","i":"k"}}},{"id":"second-b-restart","title":"The last b restarts again","codeLine":5,"summary":"The final b scans t a third time and finds nothing left, so it stays unmatched. A long s would re-scan t on every character.","state":{"s":"aba","i":2,"ch":"b","labels":{"s":"t","i":"k"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const used = [false, false, false];\nlet unmatched = 0;\nfor (const ch of s) {\n    let found = false;\n    for (let k = 0; k < 3; k++) {\n        if (t[k] === ch && used[k] === false) {\n            used[k] = true;\n            found = true;\n        }\n    }\n    if (found === false) {\n        unmatched++;\n    }\n}\nlet leftover = 0;\nfor (const u of used) {\n    if (u === false) {\n        leftover++;\n    }\n}\nreturn (unmatched + leftover);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":11,"10":12,"11":15,"12":16,"13":17,"14":18,"15":21},"statementBundles":{"8":{"startLine":8,"endLine":10},"10":{"startLine":12,"endLine":14},"14":{"startLine":18,"endLine":20}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const used = [false, false, false];\nlet unmatched = 0;\nfor (const ch of s) {\n    let found = false;\n    for (let k = 0; k < 3; k++) {\n        if (t[k] === ch && used[k] === false) {\n            used[k] = true;\n            found = true;\n        }\n    }\n    if (found === false) {\n        unmatched++;\n    }\n}\nlet leftover = 0;\nfor (const u of used) {\n    if (u === false) {\n        leftover++;\n    }\n}\nreturn (unmatched + leftover);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":11,"10":12,"11":15,"12":16,"13":17,"14":18,"15":21},"statementBundles":{"8":{"startLine":8,"endLine":10},"10":{"startLine":12,"endLine":14},"14":{"startLine":18,"endLine":20}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Boolean> used = new ArrayList<>(List.of(false, false, false));\nint unmatched = 0;\nfor (char ch : s.toCharArray()) {\n    boolean found = false;\n    for (int k = 0; k < 3; k++) {\n        if ((t.charAt(k) == ch && Objects.equals(used.get(k), false))) {\n            used.set(k, true);\n            found = true;\n        }\n    }\n    if (Objects.equals(found, false)) {\n        unmatched++;\n    }\n}\nint leftover = 0;\nfor (Boolean u : used) {\n    if (Objects.equals(u, false)) {\n        leftover++;\n    }\n}\nreturn (unmatched + leftover);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":11,"10":12,"11":15,"12":16,"13":17,"14":18,"15":21},"statementBundles":{"8":{"startLine":8,"endLine":10},"10":{"startLine":12,"endLine":14},"14":{"startLine":18,"endLine":20}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<bool> used = new() { false, false, false };\nint unmatched = 0;\nforeach (char ch in s) {\n    bool found = false;\n    for (int k = 0; k < 3; k++) {\n        if (t[k] == ch && used[k] == false) {\n            used[k] = true;\n            found = true;\n        }\n    }\n    if (found == false) {\n        unmatched++;\n    }\n}\nint leftover = 0;\nforeach (bool u in used) {\n    if (u == false) {\n        leftover++;\n    }\n}\nreturn unmatched + leftover;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":11,"10":12,"11":15,"12":16,"13":17,"14":18,"15":21},"statementBundles":{"8":{"startLine":8,"endLine":10},"10":{"startLine":12,"endLine":14},"14":{"startLine":18,"endLine":20}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<bool> used{false, false, false};\nint unmatched = 0;\nfor (int ch : s) {\n    bool found = false;\n    for (int k = 0; k < 3; k++) {\n        if ((t[k] == ch && used[k] == false)) {\n            used[k] = true;\n            found = true;\n        }\n    }\n    if (found == false) {\n        unmatched++;\n    }\n}\nint leftover = 0;\nfor (bool u : used) {\n    if (u == false) {\n        leftover++;\n    }\n}\nreturn (unmatched + leftover);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":11,"10":12,"11":15,"12":16,"13":17,"14":18,"15":21},"statementBundles":{"8":{"startLine":8,"endLine":10},"10":{"startLine":12,"endLine":14},"14":{"startLine":18,"endLine":20}}}}}},{"id":"cost-probe","chapter":"The problem","kind":"case-probe","eyebrow":"Name the cost","title":"How many checks can s of length n force over t of length m?","workspacePanel":"trace","summary":"For s = \"abcd\" and t = \"wxyz\", each character of s starts again at t[0].","options":[{"id":"n-times-m","label":"Up to n times m, since every character of s can scan all of t","rationale":"Nothing carries between characters, so each of the n characters of s can read all m characters of t before crossing one off: n times m checks.","isCorrect":true},{"id":"n-plus-m","label":"About n plus m, one pass over each string","rationale":"That is the cost we are reaching for, but the re-scanning is still here. Each character starts t over, so the work multiplies rather than adds.","isCorrect":false},{"id":"just-m","label":"About m, since t is read only once","rationale":"t is read once per character of s, not once total. An s of n characters re-reads it n times.","isCorrect":false}],"answer":"Every character of s can scan all of t, so s of length n over t of length m costs up to n times m checks. That product is the pressure the count map removes."},{"id":"pattern-quiz","chapter":"The idea","kind":"choice","source":"pattern-recognition","eyebrow":"Spot the signal","title":"Which repeated question should the state answer?","workspacePanel":"trace","quiz":{"contract":"pattern-recognition-v1","question":"Which repeated question should the state answer?","signalPrompt":"Choose the quantity that removes the nested search.","options":[{"id":"frequency-map","label":"How many more of this letter does one string have than the other?","signal":"Every letter contributes the same count-gap question, and order never matters.","rationale":"If letters of s raise a per-letter count and letters of t lower it, the leftover gap is exactly how many copies of that letter are unmatched, read in one lookup.","isCorrect":true},{"id":"is-present","label":"Does this letter show up in both strings?","signal":"Presence answers quickly, but it cannot tell a surplus of three from a surplus of one.","rationale":"Presence would call \"aaa\" and \"a\" matched, losing the two extra copies that still need appends.","isCorrect":false},{"id":"same-order","label":"Do the two strings read the same in order?","signal":"Order feels relevant, but the answer never depends on it.","rationale":"Sorting or aligning positions costs more than one tally and changes nothing about the gaps.","isCorrect":false},{"id":"longest-run","label":"What is the longest repeated run in s?","signal":"A run length compresses one string, but not into the gap between the two.","rationale":"Each letter is weighed on its own gap, not on any run inside a single string.","isCorrect":false}],"missFeedback":"The repeated work is a count-gap question about one letter, so the saved state has to be a signed count per letter."}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which cost should we build for?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"s":"bab","seen":{"b":2,"a":1},"labels":{"seen":"balance","s":"s"}}}]}},{"id":"state-meaning","chapter":"The idea","kind":"case-probe","eyebrow":"Set up the state","title":"What does the balance map hold after both strings?","summary":"Letters of s raised counts, then letters of t lowered them; s = \"bab\", t = \"aba\".","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state-meaning-state","state":{"s":"aba","seen":{"b":1,"a":-1},"labels":{"seen":"balance","s":"t"}}}]},"options":[{"id":"signed-gap","label":"Each letter mapped to a signed gap: b to plus one, a to minus one","rationale":"s had one extra b and t had one extra a, so the gaps record both the surplus on each side and which side it sits on.","isCorrect":true},{"id":"s-only-counts","label":"The counts of s alone: b to two, a to one","rationale":"That is only the first scan. Tallying t lowers those counts, so the stored values are the gap between the two strings.","isCorrect":false},{"id":"presence-set","label":"The set of letters that appear: a and b","rationale":"A set drops the magnitudes, so it could not say each letter is off by one.","isCorrect":false}],"answer":"The map holds signed gaps: b to plus one and a to minus one. A positive value is a surplus in s, a negative value a surplus in t."},{"id":"combine-invariant","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"How do a gap of plus one and a gap of minus one combine?","summary":"b sits at plus one and a sits at minus one, and each is off by one copy.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"combine-invariant-state","state":{"s":"aba","seen":{"b":1,"a":-1},"seenHighlight":"b","labels":{"seen":"balance","s":"t"}}}]},"options":[{"id":"add-magnitudes","label":"Add their magnitudes for a total of two appends","rationale":"A surplus b needs one append on t and a surplus a needs one append on s, so the two costs add to two whatever their signs.","isCorrect":true},{"id":"sum-signed","label":"Add the signed values, so plus one and minus one make zero appends","rationale":"Signs would let a surplus on one side cancel a shortfall on the other, but both surpluses still need their own appends.","isCorrect":false},{"id":"positive-only","label":"Count only the positive gap, for one append","rationale":"A negative gap is a surplus in t, which needs an append on s just as much, so it cannot be ignored.","isCorrect":false}],"answer":"Each gap costs appends equal to its magnitude, so plus one and minus one add to two. Signs only say which string is short."},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Both strings tallied, the total still zero","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"s":"bab","seen":{"b":1,"a":-1},"steps":0,"labels":{"seen":"balance","s":"s"}}}]},"body":["s = \"bab\" raised the counts and t = \"aba\" lowered them, leaving b at plus one and a at minus one. The step total starts at zero.","Now each leftover gap is read in turn, and its magnitude is added to the total."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the sum","title":"Trace the signed balance","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"add-b","state":{"s":"bab","seen":{"b":1,"a":-1},"seenHighlight":"b","steps":0,"labels":{"seen":"balance","s":"s"}}},{"id":"add-a","state":{"s":"bab","seen":{"b":1,"a":-1},"seenHighlight":"a","steps":1,"labels":{"seen":"balance","s":"s"}}}]},"beats":[{"id":"add-b","title":"What does b's gap of plus one add?","summary":"The total is at zero, reading b's gap first.","prompt":"b sits at plus one, a surplus in s.","options":[{"id":"add-one","label":"One, raising the total to one","rationale":"s has one extra b, so one b must be appended to t: the magnitude of plus one is one.","isCorrect":true},{"id":"add-zero","label":"Nothing, because the gap is balanced by a's minus one","rationale":"The two gaps are not combined into one number; each letter's surplus is counted on its own.","isCorrect":false},{"id":"add-two","label":"Two, since a surplus needs a copy on each side","rationale":"One surplus b needs one appended b. The other gap belongs to a, counted separately.","isCorrect":false}],"answer":"The magnitude of plus one is one, so the total rises to one."},{"id":"add-a","title":"What does a's gap of minus one add?","summary":"The total is at one, now reading a's gap.","prompt":"a sits at minus one, a surplus in t.","options":[{"id":"add-one-more","label":"One, raising the total to two","rationale":"A negative gap is still a surplus, so its magnitude of one adds one more append: the total becomes two.","isCorrect":true},{"id":"add-two","label":"Two, since a is missing from t","rationale":"The gap is minus one, not minus two: t has one fewer a than s, so its magnitude adds just one.","isCorrect":false},{"id":"skip-negative","label":"Nothing, because the gap is negative","rationale":"A negative gap is a surplus in t, which costs an append on s, so it cannot be skipped.","isCorrect":false}],"answer":"The magnitude of minus one is one, so the total rises to two, which the function then returns."}]},{"id":"sign-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can the gaps just be summed as they stand?","summary":"This version builds the same signed balance, raising counts for s and lowering them for t, then adds the gaps straight into the total without touching their signs. On many inputs it lands on the right number. Watch it judge s = \"bab\" against t = \"aba\".","workspacePanel":"trace","pitfall":"The code below tallies the signed gaps correctly, but it adds each gap as-is to the total instead of adding its magnitude.","whyItMatters":"A surplus in s is a positive gap and a surplus in t is a negative gap, so summing them straight lets one side cancel the other even though each surplus still needs its own appends. Add abs(diff) for every gap so opposite surpluses both count.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"balance = {}\nfor ch in s:\n    balance[ch] = balance.get(ch, 0) + 1\nfor ch in t:\n    balance[ch] = balance.get(ch, 0) - 1\nsteps = 0\nfor diff in balance.values():\n    steps += diff\nreturn steps","steps":[{"id":"build-balance","title":"The signed balance is built correctly","codeLine":5,"summary":"s = \"bab\", t = \"aba\". After both scans, b sits at plus one and a sits at minus one, which is right.","state":{"s":"aba","seen":{"b":1,"a":-1},"labels":{"seen":"balance","s":"t"}}},{"id":"add-b-signed","title":"b adds plus one","codeLine":8,"summary":"The total starts at zero. b's gap of plus one is added straight in, so the total is one so far, which still looks right.","state":{"s":"aba","seen":{"b":1,"a":-1},"seenHighlight":"b","steps":1,"labels":{"seen":"balance","s":"t"}}},{"id":"add-a-signed","title":"Minus one cancels it, and wrong","codeLine":8,"summary":"a's gap of minus one is added straight in, dropping the total to zero. It returns 0, but s and t are off by one b and one a, so the real answer is 2.","state":{"s":"aba","seen":{"b":1,"a":-1},"seenHighlight":"a","steps":0,"labels":{"seen":"balance","s":"t"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const balance = new Map();\nfor (const ch of s) {\n    balance.set(ch, (balance.has(ch) ? balance.get(ch) : 0) + 1);\n}\nfor (const ch of t) {\n    balance.set(ch, (balance.has(ch) ? balance.get(ch) : 0) - 1);\n}\nlet steps = 0;\nfor (const diff of [...balance.values()]) {\n    steps += diff;\n}\nreturn steps;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":8,"7":9,"8":10,"9":12},"statementBundles":{"3":{"startLine":3,"endLine":4},"5":{"startLine":6,"endLine":7},"8":{"startLine":10,"endLine":11}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const balance: Map<string, number> = new Map();\nfor (const ch of s) {\n    balance.set(ch, (balance.has(ch) ? balance.get(ch)! : 0) + 1);\n}\nfor (const ch of t) {\n    balance.set(ch, (balance.has(ch) ? balance.get(ch)! : 0) - 1);\n}\nlet steps = 0;\nfor (const diff of [...balance.values()]) {\n    steps += diff;\n}\nreturn steps;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":8,"7":9,"8":10,"9":12},"statementBundles":{"3":{"startLine":3,"endLine":4},"5":{"startLine":6,"endLine":7},"8":{"startLine":10,"endLine":11}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"Map<Character, Integer> balance = new HashMap<Character, Integer>();\nfor (char ch : s.toCharArray()) {\n    balance.put(ch, (balance.getOrDefault(ch, 0) + 1));\n}\nfor (char ch : t.toCharArray()) {\n    balance.put(ch, (balance.getOrDefault(ch, 0) - 1));\n}\nint steps = 0;\nfor (Integer diff : new ArrayList<Integer>(balance.values())) {\n    steps += diff;\n}\nreturn steps;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":8,"7":9,"8":10,"9":12},"statementBundles":{"3":{"startLine":3,"endLine":4},"5":{"startLine":6,"endLine":7},"8":{"startLine":10,"endLine":11}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"Dictionary<char, int> balance = new();\nforeach (char ch in s) {\n    balance[ch] = (balance.ContainsKey(ch) ? balance[ch] : 0) + 1;\n}\nforeach (char ch in t) {\n    balance[ch] = (balance.ContainsKey(ch) ? balance[ch] : 0) - 1;\n}\nint steps = 0;\nforeach (int diff in balance.Values) {\n    steps += diff;\n}\nreturn steps;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":8,"7":9,"8":10,"9":12},"statementBundles":{"3":{"startLine":3,"endLine":4},"5":{"startLine":6,"endLine":7},"8":{"startLine":10,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"unordered_map<char, int> balance;\nfor (char ch : s) {\n    balance[ch] += 1;\n}\nfor (char ch : t) {\n    balance[ch] -= 1;\n}\nint steps = 0;\nfor (const auto& [key, diff] : balance) {\n    steps += diff;\n}\nreturn steps;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":8,"7":9,"8":10,"9":12},"statementBundles":{"3":{"startLine":3,"endLine":4},"5":{"startLine":6,"endLine":7},"8":{"startLine":10,"endLine":11}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","summary":"Strings that already match, strings that share no letters, and one letter present on both sides in different amounts: any of the three could call for special handling.","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-preview","state":{"s":"night","seen":{},"labels":{"seen":"balance","s":"s"}}}]},"body":["Two strings that are already anagrams, two that share no letters at all, and one letter present on both sides but in different amounts.","Every value in the map is a signed gap, and the total adds magnitudes. Do any of these three need a branch of their own?"]},{"id":"already-anagrams-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What does the total become when the strings already match?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"already-state","state":{"s":"thing","seen":{"n":0,"i":0,"g":0,"h":0,"t":0},"steps":0,"labels":{"seen":"balance","s":"t"}}}]},"summary":"s = \"night\", t = \"thing\", both holding the same letters once each.","options":[{"id":"all-zero","label":"Every gap is zero, so the total stays at zero with no appends","rationale":"Each letter raised by s is lowered again by t, so every gap cancels and the sum of magnitudes is zero.","isCorrect":true},{"id":"needs-equal-check","label":"It needs a separate check that the strings are already equal","rationale":"No early check is needed: the gaps already reach zero, so the loop returns zero on its own.","isCorrect":false},{"id":"counts-length","label":"It returns the length of the strings, since every letter was touched","rationale":"Touching a letter twice in opposite directions leaves a gap of zero. The balance stores the leftover difference after both scans.","isCorrect":false}],"answer":"Every gap cancels to zero, so the total is zero and no special equality branch is needed."},{"id":"disjoint-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What does the total collect when no letters are shared?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"disjoint-state","state":{"s":"abc","seen":{"a":1,"b":1,"c":1,"d":-1,"e":-1,"f":-1},"steps":0,"labels":{"seen":"balance","s":"s"}}}]},"summary":"s = \"abc\", t = \"def\", with no letter appearing on both sides.","options":[{"id":"all-six","label":"All six gaps, positive and negative, for a total of six","rationale":"Nothing cancels, so each of the three letters in s stays at plus one and each in t at minus one, and the six magnitudes add to six.","isCorrect":true},{"id":"only-positive","label":"Only the three positive gaps from s, for a total of three","rationale":"The negative gaps are surpluses in t that each need an append on s, so they count too.","isCorrect":false},{"id":"zero-no-overlap","label":"Zero, since no letter is shared to compare","rationale":"An unshared letter is a pure surplus. Each copy has to be appended to the other string.","isCorrect":false}],"answer":"It collects all six magnitudes for a total of six. With no overlap, the answer is just the two lengths added."},{"id":"different-counts-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What gap does a shared letter with extra copies leave?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"different-state","state":{"s":"aaa","seen":{"a":-1},"seenHighlight":"a","steps":1,"labels":{"seen":"balance","s":"s"}}}]},"summary":"s = \"aaa\", t = \"aaaa\", so a is present on both sides but four times against three.","options":[{"id":"gap-of-one","label":"A gap of minus one, for one append","rationale":"Three raises and four lowers leave a at minus one, so its magnitude of one is the single append needed.","isCorrect":true},{"id":"gap-zero-present","label":"A gap of zero, since a appears in both strings","rationale":"Presence is not enough: four copies against three leave a real surplus of one, not zero.","isCorrect":false},{"id":"gap-seven","label":"A gap of seven, the total number of a copies","rationale":"The gap is the difference between the counts, three and four, not their sum.","isCorrect":false}],"answer":"The gap is minus one, the difference in copies, so one append covers it. Magnitude, not presence, is what the count tracks."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Two scans build the gaps, and one sum of magnitudes carries the whole answer.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"s":"bab","seen":{"b":1,"a":-1},"steps":0,"labels":{"seen":"balance","s":"s"}}}]},"body":["Raise a per-letter count for every character of s and lower it for every character of t, then walk the leftover gaps and add the magnitude of each one to a total that started at zero."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the signed balance","summary":"Now build it: make the per-letter balance map, raise it for each character of s and lower it for each of t, start a total at zero, then walk the leftover gaps adding each one's magnitude before returning the total.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"Let s raise counts and t lower them, then sum the magnitudes, and the leftover gaps are the appends.","workspacePanel":"code","body":["Two anagrams have identical letter counts, so the distance between two strings is the per-letter gap between their counts. A signed balance, raised by one string and lowered by the other, holds every gap at once.","The sign records which string is short; the magnitude records how many copies. Summing the magnitudes counts every unmatched copy in one O(n + m) pass, down from the O(n times m) of re-searching."],"takeaways":[{"title":"One signed balance, two scans","body":"Raising for s and lowering for t leaves each letter's gap in a single tally, with no second pass over either string."},{"title":"Magnitudes, not signed sums","body":"A surplus in s and a surplus in t both cost appends, so adding magnitudes keeps opposite gaps from cancelling."},{"title":"Order never enters it","body":"Anagrams ignore order, so the gaps depend only on counts and no positions are ever compared."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
