{"id":"number-of-ways-to-select-buildings","title":"Number of Ways to Select Buildings","difficulty":"medium","patterns":["prefix-sum","dp-1d"],"primaryConcept":"array-prefix-sum-basics","concepts":["array-prefix-sum-basics"],"problemForm":"core","companies":["Amazon","Google","Microsoft"],"category":"dynamic-programming","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"string","primaryParam":"s","sizeMetric":"length","constraints":["binary-string"],"sizes":[8,16,32,64]},"description":"You are given a binary string `s` where `0` represents an office building and `1` represents a restaurant. Return the number of ways to choose three buildings with indices `i < j < k` so that no two consecutive selected buildings have the same type.\n\nValid selections therefore form either pattern `010` or pattern `101`.","examples":[{"input":"s = \"001101\"","output":"6","explanation":"There are six valid triples that form 010 or 101."},{"input":"s = \"11100\"","output":"0","explanation":"No valid alternating triple can be selected."},{"input":"s = \"10101\"","output":"5","explanation":"There are four 101 triples and one 010 triple."}],"constraints":[{"id":"1-len-s-10-5","text":"1 <= len(s) <= 10^5","check":{"kind":"sizeRange","target":"s","measure":"stringLength","min":1,"max":100000}},{"id":"s-i-is-either-0-or-1","text":"s[i] is either '0' or '1'","check":{"kind":"domain","target":"s","selector":"stringChars","allowed":["0","1"]}}],"starterCode":"class Solution:\n    def numberOfWays(self, s: str) -> int:\n        # Your code here\n        pass","functionName":"numberOfWays","testCases":[{"id":"1","input":{"s":"001101"},"expected":6,"description":"Canonical mixed string."},{"id":"2","input":{"s":"11100"},"expected":0,"description":"No alternating triple."},{"id":"3","input":{"s":"10101"},"expected":5,"description":"Both 101 and 010 triples exist."},{"id":"4","input":{"s":"010"},"expected":1,"description":"Smallest valid 010 triple."},{"id":"5","input":{"s":"0"},"expected":0,"description":"Too short to choose three buildings."},{"id":"h1","input":{"s":"010101"},"expected":8,"description":"Alternating six-character string."},{"id":"h2","input":{"s":"000111"},"expected":0,"description":"All zeroes before all ones cannot form 010 or 101."},{"id":"h3","input":{"s":"1001"},"expected":2,"description":"Two choices for the middle zero in a 101 pattern."},{"id":"h4","input":{"s":"01010"},"expected":5,"description":"A fully alternating string has five valid triples."},{"id":"h5","input":{"s":"00100"},"expected":4,"description":"Repeated zero blocks still allow multiple 010 triples."},{"id":"topup-alternating-longer","input":{"s":"001011"},"expected":4,"description":"Alternating buildings create several 010 and 101 choices."},{"id":"topup-grouped-blocks","input":{"s":"111000111"},"expected":27,"description":"Grouped zeros and ones still count ordered triplets."}],"hints":[{"level":1,"content":"Try each building as the middle building of the triple.","revealPattern":false},{"level":2,"content":"If the middle building is 0, it needs a 1 on the left and a 1 on the right. If it is 1, it needs zeroes on both sides.","revealPattern":true},{"level":3,"content":"Keep counts of zeroes and ones seen on the left, and remaining zeroes and ones on the right.","revealPattern":true}],"guidedFlow":{"version":2,"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 triple","summary":"Enumerate all i, j, k and test whether they alternate.","decisionReason":"It tests every O(n^3) triple, which times out near n = 10^5.","complexity":{"time":"O(n^3)","space":"O(1)"},"tradeoffs":["Runs in O(n^3) time and uses O(1) space."],"isOptimal":false},{"id":"one-pass-counts","name":"One-pass side counts","summary":"Maintain counts on the left and right, and add compatible pairs for each middle building.","decisionReason":"Four side counts let each middle add its compatible flank pairs in O(1), counting every triple in one O(n) pass.","complexity":{"time":"O(n)","space":"O(1)"},"tradeoffs":["Runs in O(n) time and uses O(1) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-counts","title":"Initialize side counts","description":"Count the zeroes and ones on the right, and initialize left counts and answer to zero.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_zero_accumulator","scope":"init-total","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Starting the answer at one","Forgetting to initialize left counts"],"hint":"Before scanning, every building is still on the right side.","semanticSpec":{"intent":"Initialize numeric scan state.","doneWhen":"The answer accumulator starts at zero before the scan.","shouldFailWhen":"This step should fail if no zero accumulator is initialized.","roles":["answer count","side counts"],"mustProve":["The solution initializes a zero accumulator."],"mustNotAccept":["An answer initialized to a nonzero value."]}},{"id":"scan-middle","title":"Scan each middle building","description":"Visit each character as the possible middle of an alternating triple.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence","scope":"loop-through-nums","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Checking only adjacent triples","Skipping the first or last character without updating counts"],"hint":"Even endpoints should move from right counts to left counts.","semanticSpec":{"intent":"Scan the input sequence.","doneWhen":"The solution iterates over the building string.","shouldFailWhen":"This step should fail if the input sequence is not scanned.","roles":["input string","middle building"],"mustProve":["The traversal reads the input sequence."],"mustNotAccept":["A fixed-position check."]}},{"id":"add-compatible-pairs","title":"Add compatible side pairs","description":"For the current middle building, add the number of compatible left/right choices.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_and_additively_updates_accumulator","scope":"loop-through-nums","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Adding only one for each valid middle","Using same-type side counts instead of opposite-type side counts"],"hint":"A middle 0 contributes left ones times right ones; a middle 1 contributes left zeroes times right zeroes.","semanticSpec":{"intent":"Accumulate compatible triples during the scan.","doneWhen":"The answer is additively updated while scanning the input.","shouldFailWhen":"This step should fail if the answer is overwritten instead of accumulated.","roles":["answer count","left count","right count"],"mustProve":["The scan additively updates the accumulator."],"mustNotAccept":["A boolean existence check that ignores multiplicity."]}},{"id":"return-total","title":"Return the total","description":"Return the accumulated number of valid triples.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_terminal_accumulator","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Returning one of the side counts","Returning only the last contribution"],"hint":"The total accumulator contains all valid triples after the scan.","semanticSpec":{"intent":"Return the terminal accumulator.","doneWhen":"The function returns the accumulated answer after scanning.","shouldFailWhen":"This step should fail if a side count or temporary product is returned.","roles":["answer count","return value"],"mustProve":["The final return is the terminal accumulator."],"mustNotAccept":["Returning a side counter."]}}],"slides":[{"id":"the-task","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Count the alternating triples","workspacePanel":"problem","body":["The string s marks each building 0 for office or 1 for restaurant. Choose three positions i < j < k so no two chosen in a row share a type. That leaves exactly two shapes: 010 and 101.","The obvious way is to try every triple of positions. Watch it work, then watch what it repeats."]},{"id":"brute-force","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Try every triple","summary":"It works. Watch how it re-tests the same middle building against every pair of outer positions.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"total = 0\nfor i in range(len(s)):\n    for j in range(i + 1, len(s)):\n        for k in range(j + 1, len(s)):\n            triple = s[i] + s[j] + s[k]\n            if triple == '010' or triple == '101':\n                total += 1\nreturn total","steps":[{"id":"first-triple","title":"First triple from the front","codeLine":5,"summary":"i, j, k = 0, 1, 2 reads s[0..2] = \"001\". That is neither 010 nor 101, so total stays 0.","state":{"s":"001101","i":0,"j":1,"current":2,"total":0,"labels":{"current":"k"}}},{"id":"fix-the-middle","title":"The same middle, a new outer pair","codeLine":5,"summary":"With j fixed at 2, the loops keep trying one outer pair at a time: every i before it paired with every k after it, re-reading this same middle building on each attempt.","state":{"s":"001101","i":0,"j":2,"current":4,"total":1,"labels":{"current":"k"}}},{"id":"all-triples","title":"Every middle re-tries every outer pair","codeLine":5,"summary":"Three nested loops over six positions: each middle building is paired against all outer positions, one pair at a time, with a fresh string compare each time.","state":{"s":"001101","i":3,"j":4,"current":5,"total":4,"labels":{"current":"k"}}}],"body":["Pick three positions in order, glue their types into a string, and count it when it reads 010 or 101."],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let total = 0;\nfor (let i = 0; i < s.length; i++) {\n    for (let j = (i + 1); j < s.length; j++) {\n        for (let k = (j + 1); k < s.length; k++) {\n            const triple = (s[i] + s[j]) + s[k];\n            if (triple === \"010\" || triple === \"101\") {\n                total++;\n            }\n        }\n    }\n}\nreturn total;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":12},"statementBundles":{"7":{"startLine":7,"endLine":11}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let total = 0;\nfor (let i = 0; i < s.length; i++) {\n    for (let j = (i + 1); j < s.length; j++) {\n        for (let k = (j + 1); k < s.length; k++) {\n            const triple = (s[i] + s[j]) + s[k];\n            if (triple === \"010\" || triple === \"101\") {\n                total++;\n            }\n        }\n    }\n}\nreturn total;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":12},"statementBundles":{"7":{"startLine":7,"endLine":11}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int total = 0;\nfor (int i = 0; i < s.length(); i++) {\n    for (int j = (i + 1); j < s.length(); j++) {\n        for (int k = (j + 1); k < s.length(); k++) {\n            String triple = (String.valueOf(s.charAt(i)) + String.valueOf(s.charAt(j))) + String.valueOf(s.charAt(k));\n            if ((\"010\".equals(triple) || \"101\".equals(triple))) {\n                total++;\n            }\n        }\n    }\n}\nreturn total;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":12},"statementBundles":{"7":{"startLine":7,"endLine":11}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int total = 0;\nfor (int i = 0; i < s.Length; i++) {\n    for (int j = i + 1; j < s.Length; j++) {\n        for (int k = j + 1; k < s.Length; k++) {\n            string triple = s[i].ToString() + s[j].ToString() + s[k].ToString();\n            if (triple == \"010\" || triple == \"101\") {\n                total++;\n            }\n        }\n    }\n}\nreturn total;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":12},"statementBundles":{"7":{"startLine":7,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int total = 0;\nfor (int i = 0; i < s.size(); i++) {\n    for (int j = (i + 1); j < s.size(); j++) {\n        for (int k = (j + 1); k < s.size(); k++) {\n            string triple = to_string(((s[i] + s[j]) + s[k]));\n            if ((triple == string(\"010\") || triple == string(\"101\"))) {\n                total++;\n            }\n        }\n    }\n}\nreturn total;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":12},"statementBundles":{"7":{"startLine":7,"endLine":11}}}}}},{"id":"cost-probe","chapter":"The problem","kind":"case-probe","eyebrow":"Name the cost","title":"How many triples does this test?","workspacePanel":"trace","summary":"The code picks i, then j, then k, choosing each from the remaining positions of s. With three nested loops over the string, estimate how those choices compound as s grows.","options":[{"id":"n-cubed","label":"About n choose 3, which grows like n cubed","rationale":"Every distinct i < j < k gets its own string compare. At n = 10^5 that is on the order of 10^15 triples, far past what runs in time.","isCorrect":true},{"id":"n-squared","label":"About n squared, one pass per pair","rationale":"Two loops would be n squared, but there are three indices here. The innermost k loop multiplies in another factor of n.","isCorrect":false},{"id":"linear","label":"About n, one compare per character","rationale":"A single character touches many triples as i, as j, and as k. One pass cannot enumerate every ordered triple of positions.","isCorrect":false}],"answer":"Counting every ordered triple is O(n^3). The fix has to count without enumerating each triple one at a time."},{"id":"pattern-quiz","chapter":"The idea","kind":"choice","source":"pattern-recognition","eyebrow":"Spot the pattern","title":"Which idea turns one scan into the count?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"fixed-middle-preview","state":{"s":"001101","current":2,"labels":{"current":"middle"},"leftRegion":"00","rightRegion":"101"}}]},"quiz":{"contract":"pattern-recognition-v1","question":"Which idea turns one scan into the count?","signalPrompt":"The brute force kept re-pairing outer positions around one repeated role. Which idea collapses that repeated work into a single left-to-right pass?","options":[{"id":"prefix-suffix-counts","label":"Anchor each position once and count its compatible buildings on each side","signal":"Each triple has one inner position; anchoring there reduces both flanks to running counts.","rationale":"Pin each position as the inner building of a triple, then its type forces the type both flanks must be. The triples through it are how many compatible buildings sit left times how many sit right, and both counts come from one left-to-right scan.","isCorrect":true},{"id":"sort-string","label":"Sort the characters, then count blocks of 0s and 1s","signal":"Grouping the types feels like it should simplify the count.","rationale":"Sorting destroys the position order that i < j < k depends on. A triple exists because of the buildings' positions in the string.","isCorrect":false},{"id":"stack","label":"Push buildings on a stack and match them","signal":"Matching pairs is a stack reflex.","rationale":"There is no nesting to balance here. Nothing opens and later closes; a fixed middle with two flanks is not a stack shape.","isCorrect":false},{"id":"binary-search","label":"Binary search for the split point","signal":"A split into left and right hints at searching for a boundary.","rationale":"Nothing here is sorted or monotone, so there is no boundary to binary search for. The split is just every position taking its turn as the middle.","isCorrect":false}],"missFeedback":"Fix the middle. Its type forces the type each flank must be, so the triples through it are a count on the left times a count on the right."}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"side-count-contrast","state":{"s":"001101","current":2,"labels":{"current":"middle"},"left0":2,"left1":0,"right0":1,"right1":2}}]}},{"id":"state-setup","chapter":"The idea","kind":"case-probe","eyebrow":"Set up the state","title":"What must the scan carry for each middle?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state-setup-state","state":{"s":"001101","current":2,"left0":2,"left1":0,"right0":1,"right1":2}}]},"summary":"Standing on the middle at index 2, a 1, which needs a 0 on each side.","options":[{"id":"four-counts","label":"How many 0s and how many 1s lie to its left, and how many of each lie to its right","rationale":"Four running tallies, call them left0, left1, right0, right1. A middle 1 multiplies left0 by right0; a middle 0 multiplies left1 by right1. Each is one O(1) read.","isCorrect":true},{"id":"just-seen","label":"Whether a 0 and a 1 have each appeared on the left","rationale":"A yes/no flag cannot multiply. The count of valid triples is a product, so each side needs how many, not whether any.","isCorrect":false},{"id":"indices","label":"The index of every 0 and every 1 seen so far","rationale":"Storing positions answers where, but the triple count only needs how many compatible buildings flank the middle. Counts collapse those lists to four numbers.","isCorrect":false}],"answer":"Carry left0, left1 and right0, right1. As the middle moves right, the building it leaves crosses from a right count into the matching left count."},{"id":"compat-invariant","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"For a middle 1, which two counts multiply?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"invariant-state","state":{"s":"001101","current":2,"labels":{"current":"middle 1"},"left0":2,"right0":1}}]},"summary":"The middle at index 2 is a 1, so a valid triple around it reads 0, 1, 0.","options":[{"id":"opposite-type","label":"left0 times right0, the 0s on each side","rationale":"A 1 in the middle of an alternating triple is flanked by 0s. Two 0s on the left and one on the right give 2 times 1 = 2 triples through this position.","isCorrect":true},{"id":"same-type","label":"left1 times right1, the 1s on each side","rationale":"Two 1s next to a 1 would read 111, which has equal neighbors and is not allowed. The flanks must be the opposite type of the middle.","isCorrect":false},{"id":"mixed","label":"left0 times right1, a 0 on the left and a 1 on the right","rationale":"That builds 011, whose last two buildings match. Both flanks of a middle 1 must be 0, so both counts are 0 counts.","isCorrect":false}],"answer":"A middle 1 contributes left0 times right0; a middle 0 contributes left1 times right1. The middle's type fixes the opposite type on both sides."},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Everything starts on the right","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"s":"001101","left0":0,"left1":0,"right0":3,"right1":3,"total":0}}]},"body":["Before the scan, no building is to the left of any middle, so left0 and left1 are 0 and the right counts hold the whole string: three 0s and three 1s.","Each step lands on the next middle, first subtracting it from its right count, then adding the product of the two opposite-type flanks to total, then folding it into the left count."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the count","title":"Trace the middle walk","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-middle","state":{"s":"001101","current":0,"left0":0,"left1":0,"right0":2,"right1":3,"total":0}},{"id":"middle-one","state":{"s":"001101","current":2,"left0":2,"left1":0,"right0":1,"right1":2,"total":2}},{"id":"middle-zero","state":{"s":"001101","current":4,"left0":2,"left1":2,"right0":0,"right1":1,"total":6}}]},"beats":[{"id":"first-middle","title":"Why does the first middle add nothing?","summary":"The scan lands on index 0, a 0, with right0 dropped to 2.","prompt":"The middle is a 0, so it wants 1s on both sides.","options":[{"id":"no-left","label":"left1 is 0, so left1 times right1 is 0","rationale":"A middle 0 needs a 1 on its left, but nothing sits left of index 0. With no left flank possible, no triple can be centered here.","isCorrect":true},{"id":"no-right","label":"right1 is 0, so the right side is empty","rationale":"right1 is still 3 here. The flank that is missing is the left one, since the middle is at the very front.","isCorrect":false},{"id":"wrong-type","label":"A 0 in the middle is never valid","rationale":"A middle 0 is valid in a 101 triple. It just needs 1s flanking it, and there is no room on the left yet.","isCorrect":false}],"answer":"Contribution 0: an endpoint can never be the middle of a triple, and the empty left flank makes the product 0 automatically."},{"id":"middle-one","title":"What triples does this middle 1 count?","summary":"Index 2 holds a 1, with left0 = 2 compatible 0s behind it and right0 = 1 ahead of it.","prompt":"A middle 1 reads 0, 1, 0, so it needs a 0 on each side. How do its two left 0s and one right 0 combine into triples?","options":[{"id":"two-zero-one","label":"2 times 1 = 2 triples, each reading 0, 1, 0","rationale":"Either of the two left 0s pairs with the single right 0 to flank this 1, so total climbs by 2. The product counts the choices without listing them.","isCorrect":true},{"id":"all-ones","label":"0, because the surrounding buildings are 1s","rationale":"The middle is the 1; its flanks are the 0s counted by left0 and right0. Those are 2 and 1, not 0.","isCorrect":false},{"id":"one-each","label":"1, since only one triple can use any middle","rationale":"A single middle can anchor many triples, one per compatible left-right pair. Two left 0s and one right 0 give two distinct pairs.","isCorrect":false}],"answer":"total becomes 2. Multiplying the flank counts is how one middle stands in for every triple it can center."},{"id":"middle-zero","title":"Why does this middle multiply the two side counts?","summary":"Index 4 is a 0 with left1 = 2 and right1 = 1. How should those two counts combine?","prompt":"This middle 0 contributes from left1 and right1.","options":[{"id":"independent-choice","label":"Each compatible left building can pair with each compatible right building","rationale":"Two left 1s and one right 1 give 2 times 1 = 2 independent left-right pairings. Adding would count one side and forget the other side multiplies the choices.","isCorrect":true},{"id":"same-thing","label":"No reason, the result is the same either way","rationale":"2 plus 1 is 3, but the real count of pairs is 2 times 1 = 2. Addition and multiplication diverge the moment either side exceeds 1.","isCorrect":false},{"id":"right-only","label":"The left side is already counted, so only the right matters","rationale":"Neither side is counted alone. For each left building, each right building forms a separate triple with this middle.","isCorrect":false}],"answer":"total reaches 6, the final answer. Each middle contributes the product of its two flank counts, and the products sum across the scan."}]},{"id":"same-type-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can counting only 010 cover every alternating triple?","summary":"The loop below handles one of the two alternating shapes. Run it on s = \"101\", whose answer is 1.","workspacePanel":"trace","pitfall":"The code below adds left0 * right0 around each middle 1, which counts 010 triples, and leaves the middle-0 branch empty.","whyItMatters":"There are two valid shapes. A middle 1 contributes left0 * right0 for 010, and a middle 0 contributes left1 * right1 for 101. The loop must handle both middle values or it misses every triple of the omitted shape.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"right0 = 0\nright1 = 0\nfor ch in s:\n    if ch == '0':\n        right0 += 1\n    else:\n        right1 += 1\nleft0 = left1 = total = 0\nfor ch in s:\n    if ch == '1':\n        right1 -= 1\n        total += left0 * right0\n        left1 += 1\n    else:\n        right0 -= 1\n        left0 += 1\nreturn total","steps":[{"id":"front-zero","title":"The first 1 has no left flank","codeLine":12,"summary":"s = \"101\". At index 0, left0 is 0, so left0 * right0 adds 0. The loop then records this 1 on the left.","state":{"s":"101","current":0,"right0":1,"right1":1,"left0":0,"left1":1,"total":0}},{"id":"stale-right-count","title":"The middle 0 contributes nothing","codeLine":15,"summary":"Index 1 is the middle of the valid 101 triple. It should add left1 * right1 = 1 * 1, but the middle-0 branch only updates the counts, so total stays 0.","state":{"s":"101","current":1,"right0":0,"right1":1,"left0":1,"left1":1,"total":0}},{"id":"wrong-total","title":"The run ends at 0","codeLine":12,"summary":"The last 1 also has no 0 to its right, so it adds 0. The loop returns 0 even though indices 0, 1, and 2 form one valid 101 triple.","state":{"s":"101","current":2,"right0":0,"right1":0,"left0":1,"left1":2,"total":0}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let right0 = 0;\nlet right1 = 0;\nfor (const ch of s) {\n    if (ch === \"0\") {\n        right0++;\n    } else {\n        right1++;\n    }\n}\nconst value = 0;\nlet left0 = value;\nlet left1 = value;\nlet total = value;\nfor (const ch of s) {\n    if (ch === \"1\") {\n        right1--;\n        total += (left0 * right0);\n        left1++;\n    } else {\n        right0--;\n        left0++;\n    }\n}\nreturn total;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":10,"9":14,"10":15,"11":16,"12":17,"13":18,"14":19,"15":20,"16":21,"17":24},"statementBundles":{"7":{"startLine":7,"endLine":9},"8":{"startLine":10,"endLine":13},"16":{"startLine":21,"endLine":23}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let right0 = 0;\nlet right1 = 0;\nfor (const ch of s) {\n    if (ch === \"0\") {\n        right0++;\n    } else {\n        right1++;\n    }\n}\nconst value = 0;\nlet left0 = value;\nlet left1 = value;\nlet total = value;\nfor (const ch of s) {\n    if (ch === \"1\") {\n        right1--;\n        total += (left0 * right0);\n        left1++;\n    } else {\n        right0--;\n        left0++;\n    }\n}\nreturn total;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":10,"9":14,"10":15,"11":16,"12":17,"13":18,"14":19,"15":20,"16":21,"17":24},"statementBundles":{"7":{"startLine":7,"endLine":9},"8":{"startLine":10,"endLine":13},"16":{"startLine":21,"endLine":23}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int right0 = 0;\nint right1 = 0;\nfor (char ch : s.toCharArray()) {\n    if (ch == '0') {\n        right0++;\n    } else {\n        right1++;\n    }\n}\nint value = 0;\nint left0 = value;\nint left1 = value;\nint total = value;\nfor (char ch : s.toCharArray()) {\n    if (ch == '1') {\n        right1--;\n        total += (left0 * right0);\n        left1++;\n    } else {\n        right0--;\n        left0++;\n    }\n}\nreturn total;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":10,"9":14,"10":15,"11":16,"12":17,"13":18,"14":19,"15":20,"16":21,"17":24},"statementBundles":{"7":{"startLine":7,"endLine":9},"8":{"startLine":10,"endLine":13},"16":{"startLine":21,"endLine":23}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int right0 = 0;\nint right1 = 0;\nforeach (char ch in s) {\n    if (ch == '0') {\n        right0++;\n    } else {\n        right1++;\n    }\n}\nint value = 0;\nint left0 = value;\nint left1 = value;\nint total = value;\nforeach (char ch in s) {\n    if (ch == '1') {\n        right1--;\n        total += left0 * right0;\n        left1++;\n    } else {\n        right0--;\n        left0++;\n    }\n}\nreturn total;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":10,"9":14,"10":15,"11":16,"12":17,"13":18,"14":19,"15":20,"16":21,"17":24},"statementBundles":{"7":{"startLine":7,"endLine":9},"8":{"startLine":10,"endLine":13},"16":{"startLine":21,"endLine":23}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int right0 = 0;\nint right1 = 0;\nfor (int ch : s) {\n    if (ch == '0') {\n        right0++;\n    } else {\n        right1++;\n    }\n}\nint value = 0;\nint left0 = value;\nint left1 = value;\nint total = value;\nfor (int ch : s) {\n    if (ch == '1') {\n        right1--;\n        total += (left0 * right0);\n        left1++;\n    } else {\n        right0--;\n        left0++;\n    }\n}\nreturn total;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":10,"9":14,"10":15,"11":16,"12":17,"13":18,"14":19,"15":20,"16":21,"17":24},"statementBundles":{"7":{"startLine":7,"endLine":9},"8":{"startLine":10,"endLine":13},"16":{"startLine":21,"endLine":23}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Two inputs that probe the counts","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-all-same-setup","state":{"s":"1111","left0":0,"left1":0,"right0":0,"right1":4,"total":0}}]},"body":["The scan walks once, subtracting the current building from a right count and adding a product. Two kinds of input are worth pushing on it before trusting it.","Try an all-1s string, then a long alternating string. The probes ahead ask what the scan returns on the first and how wide the accumulator must be for the second."]},{"id":"all-same-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What does the scan return for all 1s?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-same-state","state":{"s":"1111","current":2,"left0":0,"left1":2,"right0":0,"right1":1,"total":0}}]},"summary":"s = \"1111\". Every middle is a 1, which contributes left0 times right0.","options":[{"id":"zero-automatic","label":"0, because left0 and right0 stay 0 the whole scan","rationale":"No 0 ever appears, so the opposite-type flank counts are always 0 and every product is 0. The general formula returns the right answer with no guard.","isCorrect":true},{"id":"needs-guard","label":"It needs an explicit check for all-same strings","rationale":"No special case is needed. The opposite-type counts are already 0, so the products are 0 and total never moves.","isCorrect":false},{"id":"counts-ones","label":"It counts the 1s as triples and returns a positive number","rationale":"111 is not an alternating triple, and the formula never multiplies same-type counts. A middle 1 reads left0 and right0, both 0 here.","isCorrect":false}],"answer":"Returns 0 with no special case. The opposite-type requirement is baked into which counts each branch multiplies."},{"id":"overflow-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"Can total outgrow a 32-bit int?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"overflow-state","state":{"s":"010101","current":3,"left0":2,"left1":1,"right0":1,"right1":1,"total":5}}]},"summary":"With n up to 10^5 and many balanced 0s and 1s, each middle can contribute a product near (n/2) times (n/2).","options":[{"id":"yes-grows","label":"Yes, the total can reach the order of n cubed and needs a wide integer type","rationale":"Summing products near (n/2)^2 across n middles grows like n^3, about 10^15 at the limit. Python ints stretch, but fixed-width languages need a 64-bit accumulator.","isCorrect":true},{"id":"small-local","label":"No, each contribution is small, so the total stays small","rationale":"Each product is small, but they accumulate across n positions. A sum of many moderate products can far exceed any one of them.","isCorrect":false},{"id":"capped-by-n","label":"No, the answer is at most n","rationale":"The answer counts triples, which scale like n^3, not n. One middle alone can anchor on the order of n^2 triples.","isCorrect":false}],"answer":"Yes. The accumulator can reach n^3 scale, so a fixed-width language wants a 64-bit total even though each step looks small."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"The scan has four moves; the opposite-type pairing carries the count.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"s":"001101","left0":0,"left1":0,"right0":3,"right1":3,"total":0}}]},"body":["Start every building on the right and the answer at 0, then walk once: move the current building from its right count, add the product of its two opposite-type flanks to the total, and fold it into the matching left count."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the one-pass counter","summary":"Build the counts in order: totals on the right, running counts on the left, each middle's contribution, then the returned total.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"Fix the middle, and an O(n^3) enumeration collapses to one scan of opposite-type flank counts.","workspacePanel":"code","body":["The brute force re-paired every outer position around each middle. Fixing the middle first turns those two inner loops into a single product of counts the scan already has.","Each test sums one product per position over a single pass, so the whole count is O(n) time and O(1) space, down from the naive O(n^3)."],"takeaways":[{"title":"Fix the middle first","body":"Each valid triple has exactly one middle building, so summing over middles counts every triple once with no double counting."},{"title":"Multiply opposite types","body":"A middle 0 contributes left1 times right1 and a middle 1 contributes left0 times right0. The middle's type forces the opposite type on both flanks."},{"title":"Keep side counts","body":"The product turns two flanks of choices into a number in O(1), so the running totals replace the enumeration the triple loop performed."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
