{"id":"perfect-squares","title":"Perfect Squares","difficulty":"medium","patterns":["dp-knapsack"],"primaryConcept":"dp-knapsack-optimization","concepts":["dp-knapsack-optimization"],"problemForm":"core","companies":["Google","Amazon","Microsoft"],"category":"dynamic-programming","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"scalar","primaryParam":"n","sizeMetric":"scalar","constraints":["positive"],"sizes":[16,64,128]},"description":"Given an integer `n`, return the fewest number of perfect square numbers that sum to `n`.\n\nA perfect square is an integer like `1`, `4`, `9`, or `16`.","examples":[{"input":"n = 12","output":"3","explanation":"12 = 4 + 4 + 4."},{"input":"n = 13","output":"2","explanation":"13 = 4 + 9."}],"constraints":[{"id":"1-n-10000","text":"1 <= n <= 10000","check":{"kind":"valueRange","target":"n","selector":"value","min":1,"max":10000}}],"starterCode":"class Solution:\n    def numSquares(self, n: int) -> int:\n        # Your code here\n        pass","functionName":"numSquares","testCases":[{"id":"1","input":{"n":12},"expected":3,"description":"Three copies of 4."},{"id":"2","input":{"n":13},"expected":2,"description":"4 plus 9."},{"id":"3","input":{"n":1},"expected":1,"description":"One is already a perfect square."},{"id":"4","input":{"n":16},"expected":1,"description":"A larger exact square."},{"id":"5","input":{"n":43},"expected":3,"description":"43 can be written as 25 + 9 + 9."},{"id":"h1","input":{"n":2},"expected":2,"description":"Two ones are the only decomposition."},{"id":"h2","input":{"n":3},"expected":3,"description":"Three ones are needed for the value three."},{"id":"h3","input":{"n":5},"expected":2,"description":"Five is 4 plus 1."},{"id":"h4","input":{"n":17},"expected":2,"description":"Seventeen is 16 plus 1."},{"id":"h5","input":{"n":18},"expected":2,"description":"Eighteen is 9 plus 9."},{"id":"topup-perfect-square","input":{"n":49},"expected":1,"description":"A perfect square needs one term."},{"id":"topup-three-square-sum","input":{"n":23},"expected":4,"description":"A non-square value requires combining several square terms."}],"hints":[{"level":1,"content":"Think of each square as a reusable choice."},{"level":2,"content":"Let `dp[x]` be the fewest square count needed to sum to `x`."},{"level":3,"content":"For each current value, try every square that does not exceed it."}],"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":"greedy-largest-square","name":"Greedy largest square","summary":"Repeatedly subtract the largest square that fits.","decisionReason":"Subtracting the largest square each time is fast, but it commits to that square and misses cheaper combinations of smaller squares, so it returns the wrong count.","complexity":{"time":"O(sqrt(n))","space":"O(1)"},"tradeoffs":["Runs in O(sqrt(n)) time and uses O(1) space."],"isOptimal":false},{"id":"dp-min-squares","name":"Minimum square-count DP","summary":"Build best answers for every subtotal and keep the minimum over fitting square choices.","decisionReason":"Solve every subtotal once and keep the minimum over all fitting squares, so no square is committed to blindly and earlier answers are reused.","complexity":{"time":"O(n * sqrt(n))","space":"O(n)"},"tradeoffs":["Runs in O(n * sqrt(n)) time and uses O(n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-dp","title":"Initialize DP table","description":"Create one DP slot for every subtotal and fill it with a large sentinel.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_sentinel_indexed_state_store","scope":"init-dp","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Create an indexed DP state where every subtotal initially looks unreachable or too expensive.","doneWhen":"This step is done when the code creates a length n + 1 DP array and fills its entries with a sentinel larger than any valid answer.","shouldFailWhen":"This step should fail if the DP table is missing or if entries are initialized as already optimal.","roles":["dp table","subtotal index","sentinel value"],"mustProve":["The DP table has one slot for each value from 0 through n.","The initial non-base entries use a large sentinel value."],"mustNotAccept":["Using a single scalar instead of an indexed table.","Initializing every subtotal to 0."],"equivalentVariants":["Fill the array directly with n + 1.","Create a zero array and then assign the sentinel across all entries."],"proofSnippets":[{"id":"py-perfect-squares-init-dp","language":"python","code":"class Solution:\n    def numSquares(self, n: int) -> int:\n        dp = [0] * (n + 1)\n        for i in range(len(dp)):\n            dp[i] = n + 1"}]},"commonMistakes":["Creating only n slots instead of n + 1","Starting every subtotal as 0"],"hint":"Use a value larger than the worst valid answer as the starting cost."},{"id":"set-base-case","title":"Set zero base case","description":"Set dp[0] to 0 because zero squares are needed to sum to zero.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_zero_index_base_case","scope":"set-base-case","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Seed the zero subtotal so larger subtotals can build from it.","doneWhen":"This step is done when dp[0] is assigned 0 before the recurrence loops.","shouldFailWhen":"This step should fail if dp[0] remains at the sentinel or is assigned a nonzero cost.","roles":["zero subtotal","base case","dp table"],"mustProve":["The zero subtotal cell is explicitly set to 0.","The assignment happens before the main recurrence."],"mustNotAccept":["Leaving dp[0] at n + 1.","Setting dp[1] as the only base case."],"equivalentVariants":["Assign dp[0] = 0 after table initialization.","Use any equivalent zero-index base-state seed."],"proofSnippets":[{"id":"py-perfect-squares-base-case","language":"python","code":"class Solution:\n    def numSquares(self, n: int) -> int:\n        dp = [0] * (n + 1)\n        for i in range(len(dp)):\n            dp[i] = n + 1\n        dp[0] = 0"}]},"commonMistakes":["Forgetting the zero subtotal","Setting the base case after the transition loops"],"hint":"Every valid sum starts from dp[0] = 0."},{"id":"outer-loop","title":"Scan all subtotals","description":"Process every target subtotal from 1 through n.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_indexed_state_space","scope":"outer-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Visit subtotals in increasing order so each recurrence can read smaller solved states.","doneWhen":"This step is done when the code loops current from 1 through n after the base case.","shouldFailWhen":"This step should fail if the recurrence skips subtotals or never reaches n.","roles":["current subtotal","target n","outer loop"],"mustProve":["The code scans positive subtotal indices.","The loop reaches the final target n."],"mustNotAccept":["Only checking n directly without filling smaller states.","Stopping at n - 1."],"equivalentVariants":["Use `range(1, n + 1)` or any equivalent inclusive scan.","Use any loop variable name for the current subtotal."],"proofSnippets":[{"id":"py-perfect-squares-outer-loop","language":"python","code":"class Solution:\n    def numSquares(self, n: int) -> int:\n        dp = [0] * (n + 1)\n        for i in range(len(dp)):\n            dp[i] = n + 1\n        dp[0] = 0\n        for current in range(1, n + 1):\n            dp[current] = dp[current - 1]"}]},"commonMistakes":["Skipping smaller subtotals","Using a loop that never reaches n"],"hint":"Build the answer from the bottom up."},{"id":"inner-loop","title":"Try square choices","description":"For each subtotal, loop over square roots until the square would exceed the subtotal.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_nested_choice_state_space","scope":"inner-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Enumerate reusable square choices for each subtotal.","doneWhen":"This step is done when each current subtotal has a nested loop over candidate square roots.","shouldFailWhen":"This step should fail if only one square is considered or the square loop is outside the subtotal loop.","roles":["current subtotal","square root choice","nested loop"],"mustProve":["The square-choice loop is nested inside the subtotal loop.","Multiple fitting square choices can be considered for the same subtotal."],"mustNotAccept":["Trying only the largest square.","Trying square choices without coupling them to the current subtotal."],"equivalentVariants":["Loop square roots from 1 upward and break once the square is too large.","Use any equivalent square-choice scan bounded by the current subtotal."],"proofSnippets":[{"id":"py-perfect-squares-inner-loop","language":"python","code":"class Solution:\n    def numSquares(self, n: int) -> int:\n        dp = [0] * (n + 1)\n        for i in range(len(dp)):\n            dp[i] = n + 1\n        dp[0] = 0\n        for current in range(1, n + 1):\n            for square in range(1, current + 1):\n                dp[current] = min(dp[current], dp[current - square * square] + 1)"}]},"commonMistakes":["Using only the largest square greedily","Letting square choices exceed the current subtotal"],"hint":"For a subtotal, square roots greater than sqrt(current) cannot help."},{"id":"update-dp","title":"Write min-cost transition","description":"If a square fits, compare the current best count with dp[current - square] + 1.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"guards_and_writes_min_cost_indexed_transition","scope":"update-dp","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Keep the minimum square count for each subtotal by trying every fitting square as the last term.","doneWhen":"This step is done when the code guards oversized squares and writes dp[current] as the minimum of its current value and dp[current - square * square] + 1.","shouldFailWhen":"This step should fail if the fit guard is missing, max is used, or the current square is not counted with +1.","roles":["fit guard","current dp cell","reduced subtotal","min transition"],"mustProve":["Oversized squares do not update the current subtotal.","The recurrence reads a smaller subtotal by subtracting the square value.","The update keeps the minimum square count."],"mustNotAccept":["Overwriting dp[current] without a min comparison.","Reading dp[current - square] instead of dp[current - square * square]."],"equivalentVariants":["Break when the square exceeds current, then update only fitting squares.","Use a conditional guard around the min transition."],"proofSnippets":[{"id":"py-perfect-squares-update-dp","language":"python","code":"class Solution:\n    def numSquares(self, n: int) -> int:\n        dp = [0] * (n + 1)\n        for i in range(len(dp)):\n            dp[i] = n + 1\n        dp[0] = 0\n        for current in range(1, n + 1):\n            for square in range(1, current + 1):\n                if square * square > current:\n                    break\n                dp[current] = min(dp[current], dp[current - square * square] + 1)"}]},"commonMistakes":["Using the square root instead of the square value in the reduced index","Taking max instead of min"],"hint":"One chosen square leaves a smaller subtotal: `current-(square*square)`."},{"id":"return-result","title":"Return target answer","description":"Return the final DP value for n.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_indexed_terminal_state","scope":"return-result","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Read the target subtotal cell after all transitions and return its computed minimum count.","doneWhen":"This step is done when the code returns dp[n] after all subtotal and square-choice loops are complete.","shouldFailWhen":"This step should fail if the code returns an intermediate subtotal or the square root itself.","roles":["target subtotal","final dp cell","return value"],"mustProve":["The returned value is read from the DP cell for n.","The return happens after the min-cost transitions."],"mustNotAccept":["Returning dp[0] or dp[current].","Returning the largest square used instead of the count."],"equivalentVariants":["Return dp[n] directly when reachable.","Use a harmless sentinel guard before returning dp[n]."],"proofSnippets":[{"id":"py-perfect-squares-return-result","language":"python","code":"class Solution:\n    def numSquares(self, n: int) -> int:\n        dp = [0] * (n + 1)\n        for i in range(len(dp)):\n            dp[i] = n + 1\n        dp[0] = 0\n        for current in range(1, n + 1):\n            for square in range(1, current + 1):\n                if square * square > current:\n                    break\n                dp[current] = min(dp[current], dp[current - square * square] + 1)\n        return dp[n] if dp[n] <= n else -1"}]},"commonMistakes":["Returning the last square root tried","Returning before all subtotals have been processed"],"hint":"The target answer is stored in dp[n]."}],"slides":[{"id":"read-the-signal","chapter":"The target","kind":"info","eyebrow":"Read the problem","title":"Fewest perfect squares that sum to n","workspacePanel":"problem","body":["You get an integer n. Perfect squares are 1, 4, 9, 16, and so on. Using any number of each, add squares together to reach n with as few terms as possible, and report that count.","The same square may be reused as often as you like, which is what makes the fewest count hard to eyeball: the best answer is not always the one that starts with the biggest square that fits."]},{"id":"brute-force","chapter":"The greedy guess","kind":"code-trace","eyebrow":"The obvious way","title":"Grab the largest square that fits","summary":"It is fast and it terminates, but for n = 12 it returns four squares instead of the fewest count.","workspacePanel":"trace","body":["For n = 12, take the biggest square that fits, subtract it, and repeat until nothing is left."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def numSquares(n: int) -> int:\n    count = 0\n    while n > 0:\n        s = 1\n        while (s + 1) * (s + 1) <= n:\n            s = s + 1\n        n = n - s * s\n        count = count + 1\n    return count","steps":[{"id":"take-9","title":"12 takes a 9","codeLine":7,"summary":"9 is the largest square at most 12, so it is chosen and 12 drops to 3.","state":{"n":12,"chosen_square":9}},{"id":"take-1s","title":"3 has no square but 1","codeLine":5,"summary":"The largest square at most 3 is 1, so 3 becomes 2, then 1, then 0, spending three 1s.","state":{"n":3,"chosen_square":1}},{"id":"greedy-total","title":"Greedy spends four squares","codeLine":9,"summary":"The run was 9 + 1 + 1 + 1, a count of 4.","state":{"n":0,"count":4}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let count = 0;\nwhile (n > 0) {\n    let s = 1;\n    while (((s + 1) * (s + 1)) <= n) {\n        s = s + 1;\n    }\n    n = n - (s * s);\n    count = count + 1;\n}\nreturn count;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":8,"9":10},"statementBundles":{"6":{"startLine":5,"endLine":6},"8":{"startLine":8,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let count = 0;\nwhile (n > 0) {\n    let s = 1;\n    while (((s + 1) * (s + 1)) <= n) {\n        s = s + 1;\n    }\n    n = n - (s * s);\n    count = count + 1;\n}\nreturn count;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":8,"9":10},"statementBundles":{"6":{"startLine":5,"endLine":6},"8":{"startLine":8,"endLine":9}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int count = 0;\nwhile (n > 0) {\n    int s = 1;\n    while ((s + 1) * (s + 1) <= n) {\n        s = s + 1;\n    }\n    n = n - s * s;\n    count = count + 1;\n}\nreturn count;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":8,"9":10},"statementBundles":{"6":{"startLine":5,"endLine":6},"8":{"startLine":8,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int count = 0;\nwhile (n > 0) {\n    int s = 1;\n    while (((s + 1) * (s + 1)) <= n) {\n        s = s + 1;\n    }\n    n = n - (s * s);\n    count = count + 1;\n}\nreturn count;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":8,"9":10},"statementBundles":{"6":{"startLine":5,"endLine":6},"8":{"startLine":8,"endLine":9}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int count = 0;\nwhile (n > 0) {\n    int s = 1;\n    while (((s + 1) * (s + 1)) <= n) {\n        s = s + 1;\n    }\n    n = n - (s * s);\n    count = count + 1;\n}\nreturn count;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":7,"8":8,"9":10},"statementBundles":{"6":{"startLine":5,"endLine":6},"8":{"startLine":8,"endLine":9}}}}}},{"id":"greedy-gap","chapter":"The greedy guess","kind":"case-probe","eyebrow":"Name the gap","title":"Greedy returned 4 for n = 12. Why is that not the fewest?","workspacePanel":"trace","options":[{"id":"smaller-repeat","label":"A smaller square used more than once beats the largest one","rationale":"Three 4s make 12 in three squares. Grabbing the 9 forced three 1s after it, so committing to the largest square missed the cheaper all-4s combination.","isCorrect":true},{"id":"wrong-largest","label":"9 is not actually the largest square under 12","rationale":"9 is the largest square at most 12. The flaw is not the choice of largest, it is committing to any single square without comparing other splits.","isCorrect":false},{"id":"order","label":"Greedy should take the squares in the other order","rationale":"Order does not change a sum. 1 + 1 + 1 + 9 is still four squares; the fix is to consider every square as the last one, not to reorder.","isCorrect":false}],"answer":"4 + 4 + 4 is three squares. Greedy committed to the 9 and never compared the all-4s split, so the fewest count has to compare every fitting square.","summary":"Greedy took 9 first, then was forced into 1 + 1 + 1."},{"id":"approach-selection","chapter":"The rule","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":"approach-selection-state","state":{"nums":[null,null,null,null,null,null,null,null,null,null,null,null,null],"labels":{"nums":"dp"}}}]}},{"id":"the-table","kind":"info","chapter":"The rule","eyebrow":"Lay out the answers","title":"One entry for every value up to n","workspacePanel":"visualizer","body":["Greedy went wrong by committing to a square without comparing what the alternatives would have cost. Comparing them means knowing the fewest squares for the smaller value each choice leaves behind.","Every one of those leftovers sits between 0 and n, so keep one entry per value in that range. The entry for a value is where its answer goes once it has been worked out.","Filling the entries in increasing order means that whenever a value is reached, every smaller value it could fall back to has already been settled."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"the-table-state","state":{"nums":[null,null,null,null,null,null,null,null,null,null,null,null,null],"labels":{"nums":"dp"}}}]}},{"id":"state-meaning","chapter":"The rule","kind":"case-probe","eyebrow":"Define the table","title":"What does dp[12] mean?","summary":"A table keeps one answer for each value from 0 through n.","workspacePanel":"visualizer","options":[{"id":"fewest-terms","label":"The fewest square terms that sum to 12","rationale":"The entry stores the optimal count for that subtotal. For 12, the count is 3 because 4 + 4 + 4 uses three square terms.","isCorrect":true},{"id":"last-square","label":"The last square chosen while building 12","rationale":"Several choices can lead to the same count. The table stores only the count.","isCorrect":false},{"id":"is-square","label":"Whether 12 is itself a perfect square","rationale":"That yes-or-no fact is not enough to solve values like 12. The entry needs the fewest number of square terms.","isCorrect":false}],"answer":"dp[12] stores the fewest square terms that sum to 12.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state-meaning-state","state":{"nums":[0,1,2,3,1,2,3,4,2,1,2,3,null],"labels":{"nums":"dp","i":"value"},"i":12}}]}},{"id":"square-four-choice","chapter":"The rule","kind":"case-probe","eyebrow":"Build the rule","title":"If the last square is 4, which table entry finishes the count for 12?","summary":"At value 12, try spending one square term with value 4.","workspacePanel":"visualizer","options":[{"id":"dp-eight","label":"dp[8] + 1","rationale":"Using one 4 leaves 8 still to sum. The table already holds the fewest count for 8, and the chosen 4 adds one term.","isCorrect":true},{"id":"dp-four","label":"dp[4] + 1","rationale":"dp[4] solves the square just chosen. The remaining value after spending 4 from 12 is 8.","isCorrect":false},{"id":"dp-twelve","label":"dp[12] + 1","rationale":"That reads the value being computed before it exists. A transition must read a smaller subtotal.","isCorrect":false}],"answer":"Choosing square 4 leaves value 8, so that candidate is dp[8] + 1.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"square-four-choice-state","state":{"nums":[0,1,2,3,1,2,3,4,2,1,2,3,null],"labels":{"nums":"dp","i":"value"},"i":12}}]}},{"id":"recurrence","chapter":"The rule","kind":"case-probe","eyebrow":"Build the rule","title":"The fewest squares for a value is built from which smaller answers?","summary":"You want the fewest squares for some value c, and 1, 4, 9 are the squares that fit under it.","workspacePanel":"visualizer","options":[{"id":"one-plus-min","label":"One more than the best of c minus each square","rationale":"Spending one square sq leaves c - sq to solve. Taking the smallest of those over every fitting square and adding one gives the best for c.","isCorrect":true},{"id":"largest-only","label":"One more than the best of c minus the largest square","rationale":"That is greedy again, which already failed on 12. Every fitting square has to be tried as the last term, not only the largest.","isCorrect":false},{"id":"sum-all","label":"The best answers for c minus each square, added together","rationale":"Only one square is spent per step, not all of them. The rule takes the minimum over squares, never the sum.","isCorrect":false}],"answer":"One more than the best subtotal: dp[c] = 1 + min over fitting squares sq of dp[c - sq]. Each square choice leads to a smaller value already solved.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"recurrence-state","state":{"nums":[0,1,2,3,1,2,3,4,2,null,null,null,null],"labels":{"nums":"dp","i":"value"},"i":8}}]}},{"id":"base-and-sentinel","chapter":"The rule","kind":"case-probe","eyebrow":"Set the floor","title":"Before any work, what should the table hold for each value?","summary":"The table will hold the fewest squares for every value from 0 up to n.","workspacePanel":"visualizer","options":[{"id":"zero-and-big","label":"Value 0 is 0; every other value starts at a large sentinel","rationale":"Zero needs no squares. Everything else starts above any real count, so the recurrence only lowers a value once a real square split proves a smaller count.","isCorrect":true},{"id":"all-zero","label":"Every value starts at 0","rationale":"Then min(0, anything) stays 0 and every value falsely looks free. The table must start high so a real split can lower it.","isCorrect":false},{"id":"all-one","label":"Every value starts at 1","rationale":"Only perfect squares take one term. A value like 12 needs three, so it cannot start at a guessed 1; unsolved values must start above any real count.","isCorrect":false}],"answer":"dp[0] = 0, and every other value starts at a sentinel larger than any real count. A square split only ever lowers a value from there.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"base-and-sentinel-state","state":{"nums":[0,null,null,null,null,null,null,null,null,null,null,null,null],"labels":{"nums":"dp","i":"value"},"i":0}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Fill the table, smallest value first","workspacePanel":"visualizer","body":["The table starts with value 0 at count 0 and every other value unsolved, shown as empty.","Work upward. For each value, try every fitting square, look up the already-solved value it leaves behind, and keep one more than the smallest.","Because smaller values are filled first, every lookup the recurrence needs is already on the table."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"nums":[0,null,null,null,null,null,null,null,null,null,null,null,null],"i":1,"labels":{"nums":"dp","i":"value"}}}]}},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the table","title":"Trace the table filling for n = 12","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"value-four","state":{"nums":[0,1,2,3,null,null,null,null,null,null,null,null,null],"i":4,"labels":{"nums":"dp","i":"value"}}},{"id":"value-eight","state":{"nums":[0,1,2,3,1,2,3,4,null,null,null,null,null],"i":8,"labels":{"nums":"dp","i":"value"}}},{"id":"value-twelve","state":{"nums":[0,1,2,3,1,2,3,4,2,1,2,3,null],"i":12,"labels":{"nums":"dp","i":"value"}}}]},"beats":[{"id":"value-four","figure":"setup","title":"What is the fewest squares for value 4?","summary":"Values 0 through 3 are solved: 0, 1, 2, 3. Squares that fit are 1 and 4.","prompt":"The table reaches value 4.","options":[{"id":"one","label":"1","rationale":"Square 4 leaves value 0, solved at 0, so 1 + 0 = 1. Square 1 leaves value 3 for 1 + 3 = 4. The best is 1.","isCorrect":true},{"id":"two","label":"2","rationale":"That would be two 2s, but 2 is not a perfect square. Using the single square 4 is one term.","isCorrect":false},{"id":"four","label":"4","rationale":"That is four 1s, the count value 4 starts above. A single 4 lowers it to 1.","isCorrect":false}],"answer":"1. Square 4 equals the value and leaves 0 (count 0), so dp[4] = 1 + 0 = 1."},{"id":"value-eight","figure":"setup","title":"Value 8 with squares 1 and 4. What does the table get?","summary":"Values up to 7 are solved: 0, 1, 2, 3, 1, 2, 3, 4.","prompt":"The table reaches value 8.","options":[{"id":"two","label":"2","rationale":"Square 4 leaves value 4, solved at 1, giving 1 + 1 = 2. That is two 4s, and nothing fitting beats it.","isCorrect":true},{"id":"three","label":"3","rationale":"Square 1 plus value 7 gives 1 + 4 = 5, and other splits are no better than 2. Two 4s win at 2.","isCorrect":false},{"id":"one","label":"1","rationale":"8 is not a perfect square, so no single square reaches it. The fewest is 2.","isCorrect":false}],"answer":"2. Square 4 leaves value 4 (count 1), so dp[8] = 1 + 1 = 2, the two-4s split."},{"id":"value-twelve","figure":"setup","title":"Value 12: which fitting square gives the fewest?","summary":"dp now holds 0, 1, 2, 3, 1, 2, 3, 4, 2, 1, 2, 3 for values 0 through 11. Squares 1, 4, 9 fit.","prompt":"The table reaches the target, value 12.","options":[{"id":"three","label":"3, taking a 4 onto the best of value 8","rationale":"Square 4 leaves value 8 (count 2) for 1 + 2 = 3, the all-4s split. Square 9 leaves value 3 (count 3) for 1 + 3 = 4, so 3 wins.","isCorrect":true},{"id":"four","label":"4, taking a 9 onto the best of value 3","rationale":"Square 9 leaves value 3 (count 3) for 4 squares, which is exactly greedy's answer. Square 4 leaves value 8 (count 2) for 3, which is fewer.","isCorrect":false},{"id":"two","label":"2","rationale":"No two squares sum to 12: 4 + 4 = 8, 9 + 1 = 10, 9 + 4 = 13. The fewest is 3.","isCorrect":false}],"answer":"3. Square 4 leaves value 8 (count 2), so dp[12] = 1 + 2 = 3. The all-4s split beats greedy's 9-first count of 4."}]},{"id":"root-vs-square-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Step back by the square root we are looping?","summary":"The inner loop already runs the root from 1 upward. Reducing by that same root, dp[current - square], still fills every value and the small ones come out right. Watch value 4, where a single 4 should make the count 1.","workspacePanel":"trace","pitfall":"The code below reduces by the root square, dp[current - square], instead of by the square value dp[current - square * square].","whyItMatters":"At current = 4 with root 2, it reads dp[4 - 2] = dp[2] = 2 and records 3, missing the single 4 that gives 1. Subtract the square value, dp[current - square * square], so choosing a square as the last term leaves the correct remaining value.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"dp = [0] * (n + 1)\nfor i in range(1, n + 1):\n    dp[i] = n + 1\ndp[0] = 0\nfor current in range(1, n + 1):\n    square = 1\n    while square * square <= current:\n        dp[current] = min(dp[current], dp[current - square] + 1)\n        square = square + 1\nreturn dp[n]","steps":[{"id":"setup","title":"Table seeded, values 0 through 4","codeLine":4,"summary":"dp[0] is 0 and the rest start at the sentinel 5. Values 1, 2, 3 fill correctly: 1, 2, 3.","state":{"nums":[0,1,2,3,5],"i":0,"labels":{"nums":"dp","i":"current"}}},{"id":"root-step","title":"At value 4, root 2 steps back by 2","codeLine":8,"summary":"With root 2 the code reads dp[4 - 2] = dp[2] = 2, then records 2 + 1 = 3 for value 4.","state":{"nums":[0,1,2,3,3],"i":4,"labels":{"nums":"dp","i":"current"}}},{"id":"wrong","title":"Value 4 reports 3, not 1","codeLine":10,"summary":"A single 4 makes value 4 in one square, so dp[4] should be 1. Stepping back by the root recorded 3 instead.","state":{"nums":[0,1,2,3,3],"i":4,"labels":{"nums":"dp","i":"current"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const dp = Array((n + 1)).fill(0);\nfor (let i = 1; i < (n + 1); i++) {\n    dp[i] = (n + 1);\n}\ndp[0] = 0;\nfor (let current = 1; current < (n + 1); current++) {\n    let square = 1;\n    while ((square * square) <= current) {\n        dp[current] = Math.min(dp[current], (dp[(current - square)] + 1));\n        square = square + 1;\n    }\n}\nreturn dp[n];","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":10,"10":13},"statementBundles":{"3":{"startLine":3,"endLine":4},"9":{"startLine":10,"endLine":12}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const dp = Array((n + 1)).fill(0);\nfor (let i = 1; i < (n + 1); i++) {\n    dp[i] = (n + 1);\n}\ndp[0] = 0;\nfor (let current = 1; current < (n + 1); current++) {\n    let square = 1;\n    while ((square * square) <= current) {\n        dp[current] = Math.min(dp[current], (dp[(current - square)] + 1));\n        square = square + 1;\n    }\n}\nreturn dp[n];","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":10,"10":13},"statementBundles":{"3":{"startLine":3,"endLine":4},"9":{"startLine":10,"endLine":12}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int[] dp = new int[(n + 1)];\nfor (int i = 1; i < (n + 1); i++) {\n    dp[i] = (n + 1);\n}\ndp[0] = 0;\nfor (int current = 1; current < (n + 1); current++) {\n    int square = 1;\n    while ((square * square) <= current) {\n        dp[current] = Math.min(dp[current], (dp[(current - square)] + 1));\n        square = square + 1;\n    }\n}\nreturn dp[n];","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":10,"10":13},"statementBundles":{"3":{"startLine":3,"endLine":4},"9":{"startLine":10,"endLine":12}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> dp = Enumerable.Repeat<int>(0, n + 1).ToList();\nfor (int i = 1; i < n + 1; i++) {\n    dp[i] = n + 1;\n}\ndp[0] = 0;\nfor (int current = 1; current < n + 1; current++) {\n    int square = 1;\n    while (square * square <= current) {\n        dp[current] = Math.Min(dp[current], dp[current - square] + 1);\n        square = square + 1;\n    }\n}\nreturn dp[n];","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":10,"10":13},"statementBundles":{"3":{"startLine":3,"endLine":4},"9":{"startLine":10,"endLine":12}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> dp = vector<int>((n + 1), 0);\nfor (int i = 1; i < (n + 1); i++) {\n    dp[i] = (n + 1);\n}\ndp[0] = 0;\nfor (int current = 1; current < (n + 1); current++) {\n    int square = 1;\n    while ((square * square) <= current) {\n        dp[current] = min(dp[current], (dp[(current - square)] + 1));\n        square = square + 1;\n    }\n}\nreturn dp[n];","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":10,"10":13},"statementBundles":{"3":{"startLine":3,"endLine":4},"9":{"startLine":10,"endLine":12}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Building each value from one more square than the best value it leaves behind filled the table from zero upward.","The values that stress the rule are where a square equals the target exactly, and the smallest values where only the square 1 fits, so try a value that is itself a perfect square and a value just above 1."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"nums":[0,null,null,null,null,null,null,null,null],"i":1,"labels":{"nums":"dp","i":"value"}}}]}},{"id":"perfect-square-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What does the table get when n is itself a perfect square?","summary":"n = 9.","workspacePanel":"visualizer","options":[{"id":"one","label":"1, because the square 9 fits exactly","rationale":"The inner loop runs the root up to 3, and 3 * 3 = 9 leaves value 0 (count 0), so dp[9] = 1 + 0 = 1. A square equal to the value must be allowed.","isCorrect":true},{"id":"two","label":"3, taking a 4 onto the best of value 5","rationale":"Square 4 leaves value 5 (count 2) for 1 + 2 = 3, but the loop also tries 9 itself, which wins at 1.","isCorrect":false},{"id":"four","label":"9, nine 1s","rationale":"Nine 1s do sum to 9, but a single 9 is one square. The minimum over fitting squares is 1.","isCorrect":false}],"answer":"1. The square 9 equals the target and leaves value 0, so dp[9] = 1 + 0 = 1. The loop must let a square reach the value itself, not stop below it.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"perfect-edge-state","state":{"nums":[0,1,2,3,1,2,3,4,2,null],"i":9,"labels":{"nums":"dp","i":"value"}}}]}},{"id":"two-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What does the table get for n = 2, where only the square 1 fits?","summary":"n = 2. The squares are 1, 4, 9, and only 1 is at most 2.","workspacePanel":"visualizer","options":[{"id":"two","label":"2, two 1s","rationale":"Square 1 leaves value 1 (count 1), so dp[2] = 1 + 1 = 2. No larger square fits 2, so two 1s is the only split.","isCorrect":true},{"id":"one","label":"1","rationale":"2 is not a perfect square, so no single square reaches it. The fewest is 2.","isCorrect":false},{"id":"zero","label":"0","rationale":"0 is the count for value 0 only. Value 2 needs at least one square.","isCorrect":false}],"answer":"2. Only the square 1 fits, so dp[2] = 1 + dp[1] = 2. The inner loop's fit guard stops it before 4.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-edge-state","state":{"nums":[0,1,null],"i":2,"labels":{"nums":"dp","i":"value"}}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"One chosen square leaves the value minus that square, never minus its root.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["Make a table sized to n, every value at a sentinel except value 0 at zero squares. Work upward: for each value, try every square that fits and keep one more than the best value it leaves behind, then read off the answer for n."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-start","state":{"nums":[0,null,null,null,null,null,null,null,null,null,null,null,null],"i":1,"labels":{"nums":"dp","i":"value"}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the fewest-squares table","eyebrow":"Code the rule","summary":"Initialize the table, seed value 0, scan values upward, try every fitting square, keep the minimum split, and return dp[n].","workspacePanel":"code","checkpoints":[{"id":"init-dp","title":"Initialize the table","description":"Create one slot for every value from 0 through n and fill each with a sentinel larger than any real answer.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_sentinel_indexed_state_store","scope":"init-dp","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Create an indexed DP state where every subtotal initially looks unreachable or too expensive.","doneWhen":"This step is done when the code creates a length n + 1 DP array and fills its entries with a sentinel larger than any valid answer.","shouldFailWhen":"This step should fail if the DP table is missing or if entries are initialized as already optimal.","roles":["dp table","subtotal index","sentinel value"],"mustProve":["The DP table has one slot for each value from 0 through n.","The initial non-base entries use a large sentinel value."],"mustNotAccept":["Using a single scalar instead of an indexed table.","Initializing every subtotal to 0."],"equivalentVariants":["Fill the array directly with n + 1.","Create a zero array and then assign the sentinel across all entries."],"proofSnippets":[{"id":"py-perfect-squares-init-dp","language":"python","code":"class Solution:\n    def numSquares(self, n: int) -> int:\n        dp = [0] * (n + 1)\n        for i in range(len(dp)):\n            dp[i] = n + 1"}]},"commonMistakes":["Creating only n slots instead of n + 1","Starting every subtotal as 0"],"hint":"Use a value larger than the worst real count, such as n + 1, as the starting cost for every slot."},{"id":"set-base-case","title":"Seed value zero","description":"Set dp[0] = 0, since no squares are needed to sum to 0.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_zero_index_base_case","scope":"set-base-case","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Seed the zero subtotal so larger subtotals can build from it.","doneWhen":"This step is done when dp[0] is assigned 0 before the recurrence loops.","shouldFailWhen":"This step should fail if dp[0] remains at the sentinel or is assigned a nonzero cost.","roles":["zero subtotal","base case","dp table"],"mustProve":["The zero subtotal cell is explicitly set to 0.","The assignment happens before the main recurrence."],"mustNotAccept":["Leaving dp[0] at n + 1.","Setting dp[1] as the only base case."],"equivalentVariants":["Assign dp[0] = 0 after table initialization.","Use any equivalent zero-index base-state seed."],"proofSnippets":[{"id":"py-perfect-squares-base-case","language":"python","code":"class Solution:\n    def numSquares(self, n: int) -> int:\n        dp = [0] * (n + 1)\n        for i in range(len(dp)):\n            dp[i] = n + 1\n        dp[0] = 0"}]},"commonMistakes":["Forgetting the zero subtotal","Setting the base case after the transition loops"],"hint":"Every valid split builds up from value 0, which costs zero squares."},{"id":"outer-loop","title":"Scan values upward","description":"Walk the values from 1 through n so smaller solved values are ready when larger ones are filled.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_indexed_state_space","scope":"outer-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Visit subtotals in increasing order so each recurrence can read smaller solved states.","doneWhen":"This step is done when the code loops current from 1 through n after the base case.","shouldFailWhen":"This step should fail if the recurrence skips subtotals or never reaches n.","roles":["current subtotal","target n","outer loop"],"mustProve":["The code scans positive subtotal indices.","The loop reaches the final target n."],"mustNotAccept":["Only checking n directly without filling smaller states.","Stopping at n - 1."],"equivalentVariants":["Use `range(1, n + 1)` or any equivalent inclusive scan.","Use any loop variable name for the current subtotal."],"proofSnippets":[{"id":"py-perfect-squares-outer-loop","language":"python","code":"class Solution:\n    def numSquares(self, n: int) -> int:\n        dp = [0] * (n + 1)\n        for i in range(len(dp)):\n            dp[i] = n + 1\n        dp[0] = 0\n        for current in range(1, n + 1):\n            dp[current] = dp[current - 1]"}]},"commonMistakes":["Skipping smaller subtotals","Using a loop that never reaches n"],"hint":"Fill the table bottom up so every lookup the recurrence needs is already solved."},{"id":"inner-loop","title":"Try every fitting square","description":"For each value, loop the square root from 1 upward and stop once its square exceeds the value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_nested_choice_state_space","scope":"inner-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Enumerate reusable square choices for each subtotal.","doneWhen":"This step is done when each current subtotal has a nested loop over candidate square roots.","shouldFailWhen":"This step should fail if only one square is considered or the square loop is outside the subtotal loop.","roles":["current subtotal","square root choice","nested loop"],"mustProve":["The square-choice loop is nested inside the subtotal loop.","Multiple fitting square choices can be considered for the same subtotal."],"mustNotAccept":["Trying only the largest square.","Trying square choices without coupling them to the current subtotal."],"equivalentVariants":["Loop square roots from 1 upward and break once the square is too large.","Use any equivalent square-choice scan bounded by the current subtotal."],"proofSnippets":[{"id":"py-perfect-squares-inner-loop","language":"python","code":"class Solution:\n    def numSquares(self, n: int) -> int:\n        dp = [0] * (n + 1)\n        for i in range(len(dp)):\n            dp[i] = n + 1\n        dp[0] = 0\n        for current in range(1, n + 1):\n            for square in range(1, current + 1):\n                dp[current] = min(dp[current], dp[current - square * square] + 1)"}]},"commonMistakes":["Using only the largest square greedily","Letting square choices exceed the current subtotal"],"hint":"A root larger than the square root of the value cannot help, so stop the inner loop there."},{"id":"update-dp","title":"Keep the minimum split","description":"For a square that fits, compare the current best with one more than the value minus that square's value.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"guards_and_writes_min_cost_indexed_transition","scope":"update-dp","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Keep the minimum square count for each subtotal by trying every fitting square as the last term.","doneWhen":"This step is done when the code guards oversized squares and writes dp[current] as the minimum of its current value and dp[current - square * square] + 1.","shouldFailWhen":"This step should fail if the fit guard is missing, max is used, or the current square is not counted with +1.","roles":["fit guard","current dp cell","reduced subtotal","min transition"],"mustProve":["Oversized squares do not update the current subtotal.","The recurrence reads a smaller subtotal by subtracting the square value.","The update keeps the minimum square count."],"mustNotAccept":["Overwriting dp[current] without a min comparison.","Reading dp[current - square] instead of dp[current - square * square]."],"equivalentVariants":["Break when the square exceeds current, then update only fitting squares.","Use a conditional guard around the min transition."],"proofSnippets":[{"id":"py-perfect-squares-update-dp","language":"python","code":"class Solution:\n    def numSquares(self, n: int) -> int:\n        dp = [0] * (n + 1)\n        for i in range(len(dp)):\n            dp[i] = n + 1\n        dp[0] = 0\n        for current in range(1, n + 1):\n            for square in range(1, current + 1):\n                if square * square > current:\n                    break\n                dp[current] = min(dp[current], dp[current - square * square] + 1)"}]},"commonMistakes":["Using the square root instead of the square value in the reduced index","Taking max instead of min"],"hint":"One chosen square leaves a smaller value: read `current-(square*square)`, then add one."},{"id":"return-result","title":"Read off the answer","description":"Return the table entry for n after every value is filled.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_indexed_terminal_state","scope":"return-result","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Read the target subtotal cell after all transitions and return its computed minimum count.","doneWhen":"This step is done when the code returns dp[n] after all subtotal and square-choice loops are complete.","shouldFailWhen":"This step should fail if the code returns an intermediate subtotal or the square root itself.","roles":["target subtotal","final dp cell","return value"],"mustProve":["The returned value is read from the DP cell for n.","The return happens after the min-cost transitions."],"mustNotAccept":["Returning dp[0] or dp[current].","Returning the largest square used instead of the count."],"equivalentVariants":["Return dp[n] directly when reachable.","Use a harmless sentinel guard before returning dp[n]."],"proofSnippets":[{"id":"py-perfect-squares-return-result","language":"python","code":"class Solution:\n    def numSquares(self, n: int) -> int:\n        dp = [0] * (n + 1)\n        for i in range(len(dp)):\n            dp[i] = n + 1\n        dp[0] = 0\n        for current in range(1, n + 1):\n            for square in range(1, current + 1):\n                if square * square > current:\n                    break\n                dp[current] = min(dp[current], dp[current - square * square] + 1)\n        return dp[n] if dp[n] <= n else -1"}]},"commonMistakes":["Returning the last square root tried","Returning before all subtotals have been processed"],"hint":"The fewest squares for n is the last value the table fills."}]},{"id":"complete","kind":"complete","chapter":"Code","eyebrow":"Take it with you","title":"What to carry forward","summary":"The fewest squares for a value is one more than the fewest for that value minus a square.","workspacePanel":"code","body":["Build up from value 0, which needs zero squares: every larger value is one square on top of a smaller value you already solved.","Take the minimum over every fitting square, and subtract the square's value, not its root, when you look back."],"takeaways":[{"title":"One square on top of a solved value","body":"dp[c] = 1 + min over fitting squares of dp[c - square value] reduces the whole problem to already-computed smaller values."},{"title":"Compare every fitting square","body":"Greedy's largest-square grab returned 4 for 12 while three 4s give 3, so the rule compares all fitting squares and keeps the minimum."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored","progressRevision":"perfect-squares-2026-08-08-introduce-the-table-and-fix-its-size"}}
