{"id":"permutation-in-string","title":"Permutation in String","difficulty":"medium","patterns":["sliding-window"],"primaryConcept":"array-sliding-window-variable","concepts":["array-sliding-window-variable"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"arrays-strings","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"two-strings","primaryParam":"s2","secondaryParam":"s1","sizeMetric":"total-length","sizes":[10,20,30,40],"constraints":["anagram-hit-mix"],"alphabet":"abcd"},"description":"Given two strings `s1` and `s2`, return `true` if some permutation of `s1` appears as a contiguous substring of `s2`.\n\nIn other words, look for a window in `s2` with the same character counts as `s1`.","examples":[{"input":"s1 = \"ab\", s2 = \"eidbaooo\"","output":"true","explanation":"The substring \"ba\" is a permutation of \"ab\"."},{"input":"s1 = \"ab\", s2 = \"eidboaoo\"","output":"false","explanation":"No length-2 window has one 'a' and one 'b'."},{"input":"s1 = \"adc\", s2 = \"dcda\"","output":"true","explanation":"The substring \"cda\" has the same counts as \"adc\"."}],"constraints":[{"id":"1-len-s1-len-s2-10-4","text":"1 <= len(s1), len(s2) <= 10^4"},{"id":"s1-and-s2-consist-of-lowercase-english-letters","text":"s1 and s2 consist of lowercase English letters"}],"starterCode":"class Solution:\n    def checkInclusion(self, s1: str, s2: str) -> bool:\n        # Your code here\n        pass","functionName":"checkInclusion","testCases":[{"id":"1","input":{"s1":"ab","s2":"eidbaooo"},"expected":true,"description":"Permutation appears in the middle."},{"id":"2","input":{"s1":"ab","s2":"eidboaoo"},"expected":false,"description":"No matching window."},{"id":"3","input":{"s1":"adc","s2":"dcda"},"expected":true,"description":"Permutation appears at the end."},{"id":"4","input":{"s1":"hello","s2":"ooolleoooleh"},"expected":false,"description":"Similar letters but no full permutation."},{"id":"5","input":{"s1":"a","s2":"a"},"expected":true,"description":"Single-character match."},{"id":"hidden-1","input":{"s1":"abc","s2":"bbbca"},"expected":true,"description":"Permutation begins after repeated characters."},{"id":"hidden-2","input":{"s1":"xyz","s2":"afdgzyxksldfm"},"expected":true,"description":"Permutation uses reversed order."},{"id":"hidden-3","input":{"s1":"abcd","s2":"abc"},"expected":false,"description":"Pattern longer than source."},{"id":"h4","input":{"s1":"aab","s2":"eidbaaooo"},"expected":true},{"id":"h5","input":{"s1":"abc","s2":"ccccbbbbaaaa"},"expected":false},{"id":"topup-match-at-end","input":{"s1":"adc","s2":"zzzzcda"},"expected":true,"description":"A permutation appears only at the end of the search string."},{"id":"topup-repeated-letter-mismatch","input":{"s1":"aabc","s2":"abdcaa"},"expected":false,"description":"Repeated letters require exact window counts, not just membership."}],"hints":[{"level":1,"content":"Only windows of length len(s1) can match."},{"level":2,"content":"Compare character counts for the current fixed-size window instead of sorting each substring.","revealPattern":true},{"level":3,"content":"Seed counts for s1 and the first s2 window, then slide by adding the entering character and removing the leaving character."}],"guidedFlow":{"version":2,"progressRevision":"permutation-in-string-2026-11-20-count-rows-then-slide","approachSelection":{"contract":"approach-selection-v1","question":"How should each window of s2 be checked?","decisionPrompt":"Compare what each plan has to redo when the window moves one letter.","approaches":[{"id":"fixed-frequency-window","name":"Slide one table of counts","summary":"Count s1 and the first window once. On every move, take one off the letter that leaves, add one for the letter that enters, and compare the two tables.","decisionReason":"Neighboring windows share every letter except one at each end, so two updates keep the window's table correct. Each of the n letters of s2 enters once and leaves at most once, and the tables never hold more than 26 counts.","complexity":{"time":"O(n)","space":"O(1)"},"tradeoffs":["O(n) time for an s2 of n letters, with two fixed tables of 26 counts."],"isOptimal":true,"steps":["Count the letters of s1.","Count the first window of s2.","Compare the two tables.","Move the window one letter, update two counts, and compare again."]},{"id":"sort-each-window","name":"Sort every window","summary":"Sort the letters of s1 once, then sort each window of s2 and compare the sorted strings.","decisionReason":"Sorting a window of k letters costs k log k, and that work is thrown away when the window moves, even though only one letter left and one entered. Over the windows of an s2 of n letters that comes to O(n k log k).","complexity":{"time":"O(n k log k)","space":"O(k)"},"tradeoffs":["Every window is sorted from scratch: O(n k log k) time and O(k) extra space."],"isOptimal":false}]},"codingCheckpoints":[{"id":"init-counters","title":"Count s1 and the first window","description":"If s1 is longer than s2, return false. Otherwise count the letters of s1 into one table, and count the first stretch of s2 that is as long as s1 into a second table.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"initializes_pattern_and_window_counts","scope":"init-counters","readMode":"sliding-window-value-query-v1"}]},"commonMistakes":["Recording only which letters appear, which loses how many times each one does","Counting a first window that is longer or shorter than s1","Reading a first window out of an s2 that is shorter than s1"],"hint":"Both tables start with zero for every letter. Each letter of s1 adds one to its entry in the first table, and each letter of the first window adds one in the second.","semanticSpec":{"intent":"Initialize the two indexed count states needed for fixed-window frequency matching.","doneWhen":"Both the pattern counts and first-window counts have been populated before any comparison.","shouldFailWhen":"The code does not initialize both count states or does not seed the first fixed-size window.","roles":["pattern count state","window count state","fixed window length"],"mustProve":["A count state is seeded from s1.","A separate count state is seeded from the first pattern-length characters of the search string.","Both count states use indexed frequency updates rather than set membership."],"mustNotAccept":["Tracking only character presence.","Counting only one of the two strings.","Using a first window length unrelated to the pattern length."],"equivalentVariants":["Use arrays indexed by normalized character code.","Use dictionary or counter states keyed by character.","Seed both count states in separate loops or in one paired loop."],"proofSnippets":[{"id":"py-permutation-init-counters","language":"python","code":"def checkInclusion(s1, s2):\n    if len(s1) > len(s2):\n        return False\n    need = [0] * 26\n    window = [0] * 26\n    for ch in s1:\n        need[ord(ch) - ord('a')] += 1\n    for ch in s2[:len(s1)]:\n        window[ord(ch) - ord('a')] += 1"}]}},{"id":"check-initial","title":"Compare the first window","description":"If the first window's counts already equal the counts of s1, return true before the window moves.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"records_initial_match_index","scope":"check-initial","readMode":"sliding-window-value-query-v1"}]},"commonMistakes":["Moving the window before the first window has been compared"],"hint":"Every move produces a window that starts one index later, so the window that starts at index 0 is never produced by a move and needs its own comparison.","semanticSpec":{"intent":"Recognize when the first fixed-size window already matches the pattern counts.","doneWhen":"Pattern counts and first-window counts are compared before the sliding loop.","shouldFailWhen":"The code seeds counts but does not check the first window.","roles":["pattern count state","window count state","initial match decision"],"mustProve":["The pattern count state is seeded from s1.","The first-window count state is compared against the pattern count state."],"mustNotAccept":["Only checking windows after the first slide.","Tracking only character membership."],"equivalentVariants":["Use arrays of size 26.","Use dictionaries or counters keyed by character."],"proofSnippets":[{"id":"py-permutation-check-initial","language":"python","code":"def checkInclusion(s1, s2):\n    if len(s1) > len(s2):\n        return False\n    need = [0] * 26\n    window = [0] * 26\n    for ch in s1:\n        need[ord(ch) - ord('a')] += 1\n    for ch in s2[:len(s1)]:\n        window[ord(ch) - ord('a')] += 1\n    if window == need:\n        return True"}]}},{"id":"add-entering","title":"Add the letter that enters","description":"Move the right end of the window through the rest of s2 one index at a time, adding one to the count of each letter that enters.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"adds_entering_value_to_window_state","scope":"add-entering","readMode":"sliding-window-value-query-v1"}]},"commonMistakes":["Starting the scan at index 0, which counts the first window's letters a second time","Adding the letter one index behind the one that just entered"],"hint":"The first letter to enter is the one just after the first window. Its index equals the length of s1.","semanticSpec":{"intent":"Add the character at the advancing right edge to the active count state.","doneWhen":"Each slide increments the count for `s2[right]`.","shouldFailWhen":"The entering character is not counted or the increment uses the wrong index.","roles":["window count state","entering character"],"mustProve":["The new right-side character is added to the window count state."],"mustNotAccept":["A sliding loop that never counts the entering character."],"equivalentVariants":["Use array counters.","Use dictionary counters keyed by character."],"proofSnippets":[{"id":"py-permutation-add-entering","language":"python","code":"def checkInclusion(s1, s2):\n    if len(s1) > len(s2):\n        return False\n    need = [0] * 26\n    window = [0] * 26\n    for ch in s1:\n        need[ord(ch) - ord('a')] += 1\n    for ch in s2[:len(s1)]:\n        window[ord(ch) - ord('a')] += 1\n    if window == need:\n        return True\n    for right in range(len(s1), len(s2)):\n        window[ord(s2[right]) - ord('a')] += 1"}]}},{"id":"remove-leaving","title":"Remove the letter that leaves","description":"On the same move, take one off the count of the letter that drops out on the left, so the window stays as long as s1.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"removes_leaving_value_from_window_state","scope":"remove-leaving","readMode":"sliding-window-value-query-v1"}]},"commonMistakes":["Never removing a letter, so the table counts more letters than the window holds","Removing the letter just before the entering one instead of the one a full length of s1 behind it"],"hint":"The letter that leaves sits behind the entering letter by exactly the length of s1.","semanticSpec":{"intent":"Remove the character that falls off the left edge from the active count state.","doneWhen":"Each slide decrements the character one `s1` length behind `right`.","shouldFailWhen":"No character is removed or the decrement uses an index unrelated to the fixed window length.","roles":["window count state","leaving character","pattern length"],"mustProve":["The character one pattern length behind `right` is removed from the window count state."],"mustNotAccept":["Growing the active window without removing the expired character.","Decrementing a character that remains inside the window."],"equivalentVariants":["Use array counters.","Use dictionary counters and remove zero entries when needed for equality."],"proofSnippets":[{"id":"py-permutation-remove-leaving","language":"python","code":"def checkInclusion(s1, s2):\n    if len(s1) > len(s2):\n        return False\n    need = [0] * 26\n    window = [0] * 26\n    for ch in s1:\n        need[ord(ch) - ord('a')] += 1\n    for ch in s2[:len(s1)]:\n        window[ord(ch) - ord('a')] += 1\n    if window == need:\n        return True\n    for right in range(len(s1), len(s2)):\n        window[ord(s2[right]) - ord('a')] += 1\n        window[ord(s2[right - len(s1)]) - ord('a')] -= 1"}]}},{"id":"check-each","title":"Compare after every move","description":"Once both counts are updated, compare the window's table with the table for s1 and return true if they are equal.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"detects_matching_window_after_slide","scope":"check-each","readMode":"sliding-window-value-query-v1"}]},"commonMistakes":["Comparing between the two updates, when the table counts one letter too many or too few","Comparing only once, after the scan has finished","With counts kept in a map, keeping a letter stored at 0 after it leaves, which some maps treat as different from a letter never stored"],"hint":"A window is ready to compare when its table again counts exactly as many letters as s1 has.","semanticSpec":{"intent":"Recognize a matching fixed-size frequency window during the sliding phase.","doneWhen":"The code compares live window counts with pattern counts after each slide and returns true on a match.","shouldFailWhen":"The code slides counts but never checks the updated window.","roles":["pattern count state","window count state","match decision"],"mustProve":["The updated window state is compared against the pattern state.","A match produces a positive result."],"mustNotAccept":["Comparing before the slide update.","Checking only the first window."],"equivalentVariants":["Return true immediately on a matching window.","Set a boolean result when a matching window is found."],"proofSnippets":[{"id":"py-permutation-check-each","language":"python","code":"def checkInclusion(s1, s2):\n    if len(s1) > len(s2):\n        return False\n    need = [0] * 26\n    window = [0] * 26\n    for ch in s1:\n        need[ord(ch) - ord('a')] += 1\n    for ch in s2[:len(s1)]:\n        window[ord(ch) - ord('a')] += 1\n    if window == need:\n        return True\n    for right in range(len(s1), len(s2)):\n        window[ord(s2[right]) - ord('a')] += 1\n        window[ord(s2[right - len(s1)]) - ord('a')] -= 1\n        if window == need:\n            return True"}]}},{"id":"return-result","title":"Return false after the last window","description":"If the scan reaches the end of s2 without finding equal counts, return false.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"returns_boolean_match_result","scope":"return-result","readMode":"sliding-window-value-query-v1"}]},"commonMistakes":["Returning false as soon as one window fails to match","Ending the function without returning anything when no window matches"],"hint":"A later window can still match after one fails, so the false result belongs after the scan and outside it.","semanticSpec":{"intent":"Prove the boolean result has both a positive match return during sliding and a negative fallback after the scan is exhausted.","doneWhen":"The code returns true when a matching window is found and returns false after the sliding loop if no match exists.","shouldFailWhen":"The code omits the final false fallback or returns false before all windows are checked.","roles":["pattern count state","window count state","match decision","terminal false return"],"mustProve":["The updated window state is compared against the pattern state.","A matching window returns true from the sliding loop.","A later outer fallback returns false after the sliding loop."],"mustNotAccept":["Only handling the initial window.","Returning false inside the loop for the first non-matching window.","Falling off the end without a false result."],"equivalentVariants":["Return true immediately on a matching window, then return false after the loop.","Use equivalent fixed-window count states as long as the final miss path is after the scan."],"proofSnippets":[{"id":"py-permutation-return-result","language":"python","code":"def checkInclusion(s1, s2):\n    need = [0] * 26\n    window = [0] * 26\n    for ch in s1:\n        need[ord(ch) - ord('a')] += 1\n    for ch in s2[:len(s1)]:\n        window[ord(ch) - ord('a')] += 1\n    if window == need:\n        return True\n    for right in range(len(s1), len(s2)):\n        window[ord(s2[right]) - ord('a')] += 1\n        window[ord(s2[right - len(s1)]) - ord('a')] -= 1\n        if window == need:\n            return True\n    return False"}]}}],"slides":[{"id":"read-the-signal","kind":"info","title":"Find one string's letters, in any order, inside another","workspacePanel":"problem","body":["You get two strings. Return true if some stretch of consecutive letters in the second uses exactly the letters of the first, in any order. Return false if no stretch does.","In the example the first string, s1, is \"aab\". The bracketed stretch of the second string, s2, is \"baa\": the same letters in a different order, so the answer is true."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"task-example","state":{"s1":"aab","s":"eidbaaooo","left":3,"right":5,"labels":{"s":"s2","left":"","right":""}}}]}},{"id":"permutation-is-a-multiset","kind":"case-probe","title":"What makes \"baa\" a rearrangement of \"aab\"?","workspacePanel":"visualizer","options":[{"id":"same-counts","label":"Each letter appears the same number of times in both","rationale":"Both hold two a's and one b. Only the order differs, and a rearrangement is free to change the order.","isCorrect":true},{"id":"letters-appear","label":"Every letter of \"baa\" appears somewhere in \"aab\"","rationale":"That is also true of \"bbb\", and no reordering of \"aab\" gives \"bbb\".","isCorrect":false},{"id":"same-length","label":"Both are three letters long","rationale":"\"eid\" is three letters long too, and it shares no letter with \"aab\".","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"rearrangement-example","state":{"s1":"aab","s":"eidbaaooo","left":3,"right":5,"labels":{"s":"s2","left":"","right":""}}}]}},{"id":"window-length","kind":"case-probe","title":"Which stretches of s2 could be a rearrangement of s1?","workspacePanel":"visualizer","options":[{"id":"exactly-three","label":"Only stretches of exactly three letters","rationale":"Equal counts for every letter add up to the same number of letters, so any other length is ruled out before counting.","isCorrect":true},{"id":"three-or-more","label":"Stretches of three letters or more","rationale":"A longer stretch such as \"baao\" has four letters to count and \"aab\" has three, so the counts cannot all be equal.","isCorrect":false},{"id":"up-to-three","label":"Stretches of up to three letters","rationale":"A shorter stretch such as \"ba\" leaves one a of s1 unused, and a rearrangement uses every letter.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-of-s2","state":{"s1":"aab","s":"eidbaaooo","labels":{"s":"s2"}}}]}},{"id":"brute-force","kind":"info","title":"Check one window by counting","workspacePanel":"visualizer","body":["The three-letter stretch being checked is called the window. It can start at any index where three letters still fit.","Each window is checked with two tables of counts, one count for each of the 26 lowercase letters the strings may contain. They are drawn as two rows, showing only the six letters that occur in this example."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"count-s1","title":"Count s1 once","summary":"s1 is the same for every window, so its letters are counted a single time. The counts go in the row labeled need: two a's and one b.","state":{"s1":"aab","grid":[[2,1,0,0,0,0]],"rowLabels":["need"],"colLabels":["a","b","d","e","i","o"],"changed":[[0,0],[0,1]],"s":"eidbaaooo","labels":{"s":"s2","grid":"letter counts","left":"","right":""}}},{"id":"count-first-window","title":"Count the first window","summary":"The first three letters of s2 are counted into a second row, labeled window. It differs from the need row in five columns, so \"eid\" is not a rearrangement of s1.","state":{"s1":"aab","grid":[[2,1,0,0,0,0],[0,0,1,1,1,0]],"rowLabels":["need","window"],"colLabels":["a","b","d","e","i","o"],"changed":[[1,2],[1,3],[1,4]],"s":"eidbaaooo","left":0,"right":2,"labels":{"s":"s2","grid":"letter counts","left":"","right":""}}}]}},{"id":"recount-cost","kind":"case-probe","title":"Suppose every window is counted from scratch and none match. How many letters of s2 get read in total?","workspacePanel":"visualizer","options":[{"id":"windows-times-length","label":"21: seven windows of three letters each","rationale":"A window can start at index 0 through index 6. Each of those seven windows reads its own three letters, whatever the window before it read. For an s2 of 10,000 letters, the longest allowed, and an s1 of 5,000, that comes to about 25 million letters.","isCorrect":true},{"id":"each-letter-once","label":"9: each letter of s2 is read once","rationale":"The d at index 2 is read for \"eid\", again for \"idb\" and a third time for \"dba\".","isCorrect":false},{"id":"every-start","label":"27: nine starting indexes, three letters each","rationale":"A window starting at index 7 or 8 would run past the end of s2, so only seven starts fit.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-window-counted","state":{"s1":"aab","grid":[[2,1,0,0,0,0],[0,0,1,1,1,0]],"rowLabels":["need","window"],"colLabels":["a","b","d","e","i","o"],"s":"eidbaaooo","left":0,"right":2,"labels":{"s":"s2","grid":"letter counts","left":"","right":""}}}]}},{"id":"two-change","kind":"case-probe","title":"The next window is \"idb\". What is the least work that makes the window row correct for it?","workspacePanel":"visualizer","options":[{"id":"two-updates","label":"Take one off e and add one to b","rationale":"e is the only letter that left and b is the only one that entered. i and d are in both windows, so their counts are already right.","isCorrect":true},{"id":"recount","label":"Clear the row, then count i, d and b","rationale":"That reads three letters to change two counts. i and d were counted a moment ago and are still in the window.","isCorrect":false},{"id":"add-only","label":"Add one to b","rationale":"The row would then count four letters, e, i, d and b, while the window holds three.","isCorrect":false}],"answer":"Every move of the window is this same pair of updates, however long s1 is. When the letter that leaves and the letter that enters are the same, the two updates cancel and the row stays as it was.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"before-first-move","state":{"s1":"aab","grid":[[2,1,0,0,0,0],[0,0,1,1,1,0]],"rowLabels":["need","window"],"colLabels":["a","b","d","e","i","o"],"s":"eidbaaooo","left":0,"right":2,"labels":{"s":"s2","grid":"letter counts","left":"","right":""}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Each move is the same two updates. Follow the window across s2.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"after-first-move","state":{"s1":"aab","grid":[[2,1,0,0,0,0],[0,1,1,0,1,0]],"rowLabels":["need","window"],"colLabels":["a","b","d","e","i","o"],"changed":[[1,1],[1,3]],"s":"eidbaaooo","left":1,"right":3,"labels":{"s":"s2","grid":"letter counts","left":"","right":""}}},{"id":"slide-to-dba","state":{"s1":"aab","grid":[[2,1,0,0,0,0],[1,1,1,0,0,0]],"rowLabels":["need","window"],"colLabels":["a","b","d","e","i","o"],"changed":[[1,0],[1,4]],"s":"eidbaaooo","left":2,"right":4,"labels":{"s":"s2","grid":"letter counts","left":"","right":""}}},{"id":"slide-to-baa","state":{"s1":"aab","grid":[[2,1,0,0,0,0],[2,1,0,0,0,0]],"rowLabels":["need","window"],"colLabels":["a","b","d","e","i","o"],"changed":[[1,0],[1,2]],"s":"eidbaaooo","left":3,"right":5,"labels":{"s":"s2","grid":"letter counts","left":"","right":""}}},{"id":"return-true","state":{"s1":"aab","grid":[[2,1,0,0,0,0],[2,1,0,0,0,0]],"rowLabels":["need","window"],"colLabels":["a","b","d","e","i","o"],"s":"eidbaaooo","left":3,"right":5,"labels":{"s":"s2","grid":"letter counts","left":"","right":""},"returns":true}}]},"beats":[{"id":"leaving-index","title":"The next letter to enter is the a at index 4. Which index leaves the window?","summary":"","prompt":"","options":[{"id":"three-behind","label":"Index 1, three places behind index 4","rationale":"The window always holds three letters, the length of s1. With index 4 as its right end it starts at index 2, so the i at index 1 is out. The letter that leaves is always the length of s1 behind the one that enters: 4 - 3 = 1.","isCorrect":true},{"id":"one-behind","label":"Index 3, the one just before index 4","rationale":"Index 3 holds the b that entered on the last move, and it stays in the window for two more moves.","isCorrect":false},{"id":"start-of-s2","label":"Index 0, the start of s2","rationale":"The e at index 0 left on the last move. Taking one off e again would put its count below zero.","isCorrect":false}]},{"id":"near-miss","title":"Does the search end at the window \"dba\"?","summary":"","prompt":"","options":[{"id":"slide-again","label":"No: the rows differ, so the window moves again","rationale":"The window holds one a where the need row has two, and a d where it has none. Holding an a and a b is not enough when s1 uses a twice.","isCorrect":true},{"id":"true-has-letters","label":"Yes, with true: the window contains an a and a b","rationale":"The comparison is between counts. The a column reads 1 in the window row and 2 in the need row.","isCorrect":false},{"id":"false-has-d","label":"Yes, with false: a window with a d in it can never match","rationale":"The d leaves on the next move. Four windows are still to come, and none of them has been compared.","isCorrect":false}]},{"id":"match-found","title":"The window row now equals the need row. What does the function do?","summary":"","prompt":"","options":[{"id":"return-now","label":"Returns true now, without reading the rest of s2","rationale":"One matching window is all the problem asks for. Nothing in the last three letters can change that.","isCorrect":true},{"id":"finish-scan","label":"Moves the window to the end of s2, then returns true","rationale":"The answer is already known. Three more moves would cost six updates and change nothing.","isCorrect":false},{"id":"return-index","label":"Returns 3, the index where the match starts","rationale":"The problem asks whether a match exists. Its position is not part of the answer.","isCorrect":false}]}]},{"id":"edge-case-intro","kind":"info","title":"A solution can pass the example and still fail these three inputs","workspacePanel":"visualizer","body":["The example's match sat in the middle of s2, three moves in. Next comes an s1 longer than s2, then a match in the very first window, then an s2 made only of letters that s1 uses."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"match-in-the-middle","state":{"s1":"aab","grid":[[2,1,0,0,0,0],[2,1,0,0,0,0]],"rowLabels":["need","window"],"colLabels":["a","b","d","e","i","o"],"s":"eidbaaooo","left":3,"right":5,"labels":{"s":"s2","grid":"letter counts","left":"","right":""}}}]}},{"id":"s1-longer-edge","kind":"case-probe","title":"Here s1 is longer than s2. What should the function return?","workspacePanel":"visualizer","options":[{"id":"false-no-room","label":"false: s2 has no stretch of three letters","rationale":"A rearrangement of s1 uses all three of its letters, and s2 has room for only two. So the function can return false before it counts anything.","isCorrect":true},{"id":"true-letters-appear","label":"true: both letters of s2 appear in s1","rationale":"The requirement runs the other way. Every letter of s1 has to be found in s2, and s2 is one a short.","isCorrect":false},{"id":"true-partial","label":"true: \"ab\" matches the last two letters of s1","rationale":"That leaves the first a of s1 without a letter in s2 to pair with.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"s1-longer-state","state":{"s1":"aab","s":"ab","labels":{"s":"s2"}}}]}},{"id":"first-window-edge","kind":"case-probe","title":"Here the first window already equals the need row. When does the comparison run?","workspacePanel":"visualizer","options":[{"id":"before-and-after","label":"Once before any move, then after every move","rationale":"Moving the window produces the windows that start at index 1 and later. The window that starts at index 0 exists only before the first move. When s1 and s2 are the same length, that first comparison is the only one.","isCorrect":true},{"id":"after-every-move","label":"After every move","rationale":"The first comparison would then be on \"bax\". The window \"aba\" would be gone without ever being compared.","isCorrect":false},{"id":"after-last-move","label":"Once, after the last move","rationale":"Only the last window, \"axy\", would ever be compared.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-window-state","state":{"s1":"aab","grid":[[2,1,0,0],[2,1,0,0]],"rowLabels":["need","window"],"colLabels":["a","b","x","y"],"s":"abaxy","left":0,"right":2,"labels":{"s":"s2","grid":"letter counts","left":"","right":""}}}]}},{"id":"no-match-edge","kind":"case-probe","title":"Both windows of this s2 have been compared. What does the function return?","workspacePanel":"visualizer","options":[{"id":"false-no-window","label":"false: neither window has two a's and one b","rationale":"\"abb\" and \"bba\" each hold one a and two b's, and there is no window left to try.","isCorrect":true},{"id":"true-letters-present","label":"true: s2 contains two a's and a b","rationale":"The two a's sit at opposite ends of s2, so no three consecutive letters include both.","isCorrect":false},{"id":"true-only-s1-letters","label":"true: every letter of s2 is a letter that s1 uses","rationale":"The counts have to be equal. Each window has two b's, and s1 has one.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-match-state","state":{"s1":"aab","grid":[[2,1],[1,2]],"rowLabels":["need","window"],"colLabels":["a","b"],"s":"abba","left":1,"right":3,"labels":{"s":"s2","grid":"letter counts","left":"","right":""}}}]}},{"id":"ready-to-code","kind":"info","title":"That finishes the plan for s1 and s2. Now write the function.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["If s1 is longer than s2, the function returns false right away.","Otherwise it counts the letters of s1 into one table, and the first window of s2, as long as s1, into another. If the two tables are equal, it returns true.","Then the window moves one letter at a time to the end of s2. Each move adds one for the letter that enters and takes one off the letter that leaves, the length of s1 behind it. If the tables are now equal, it returns true.","If no window matched, it returns false after the last one."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"s1":"aab","grid":[[2,1,0,0,0,0],[0,0,1,1,1,0]],"rowLabels":["need","window"],"colLabels":["a","b","d","e","i","o"],"s":"eidbaaooo","left":0,"right":2,"labels":{"s":"s2","grid":"letter counts","left":"","right":""}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Write the sliding count","workspacePanel":"code"},{"id":"complete","kind":"complete","title":"A rearrangement is a window with the same letter counts","workspacePanel":"code","takeaways":[{"title":"Compare letter counts","body":"A window matches when every letter appears in it as often as in s1. \"baa\" matches \"aab\", while \"dba\" and \"abb\" hold some of the right letters in the wrong amounts."},{"title":"One letter leaves, one enters","body":"Moving the window takes one off the count of the letter that leaves and adds one for the letter that enters. The letter that leaves sits exactly the length of s1 behind the one that enters."},{"title":"Compare the first window, then after every move","body":"The first window exists before any move, so it gets its own comparison. false is returned only once the last window has failed."},{"title":"O(n) time and O(1) space","body":"Each letter of s1 is counted once, and each letter of s2 enters the window at most once and leaves at most once. A comparison looks at 26 counts, so the work grows in step with n, the length of s2. Reading the first window by index needs no copy of it, so the two tables of 26 counts are the only extra memory. Counting every window from scratch reads k letters per window for an s1 of k letters, O(n × k) in all."}]}],"slidesOrigin":"authored"}}
