{"id":"longest-square-streak-in-an-array","title":"Longest Square Streak in an Array","difficulty":"medium","patterns":["hash-map"],"primaryConcept":"hash-map-complements","concepts":["hash-map-complements"],"problemForm":"core","companies":["Google","Amazon","Microsoft"],"category":"hash-tables","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"nums","sizeMetric":"length","constraints":["positive"],"valueRange":{"min":2,"max":100000},"sizes":[8,16,32,64]},"description":"Given an integer array `nums`, return the length of the longest square streak in `nums`, or `-1` if no square streak exists.\n\nA square streak is a sequence of at least two numbers where each next number equals the square of the previous number. The values do not need to be adjacent in the original array.","examples":[{"input":"nums = [4,3,6,16,8,2]","output":"3","explanation":"The longest streak is 2 -> 4 -> 16."},{"input":"nums = [2,3,5,6,7]","output":"-1","explanation":"No value has its square present, so there is no streak of length at least two."},{"input":"nums = [10,100,10000,3,9,81]","output":"3","explanation":"Both 10 -> 100 -> 10000 and 3 -> 9 -> 81 have length 3."}],"constraints":[{"id":"2-len-nums-10-5","text":"2 <= len(nums) <= 10^5","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":2,"max":100000}},{"id":"2-nums-i-10-5","text":"2 <= nums[i] <= 10^5","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":2,"max":100000}}],"starterCode":"class Solution:\n    def longestSquareStreak(self, nums: list[int]) -> int:\n        # Your code here\n        pass","functionName":"longestSquareStreak","testCases":[{"id":"1","input":{"nums":[4,3,6,16,8,2]},"expected":3,"description":"Standard chain with values out of order."},{"id":"2","input":{"nums":[2,3,5,6,7]},"expected":-1,"description":"No square relationship."},{"id":"3","input":{"nums":[10,100,10000,3,9,81]},"expected":3,"description":"Two streaks tie for best length."},{"id":"4","input":{"nums":[2,4,16,256,65536]},"expected":5,"description":"Long power chain."},{"id":"5","input":{"nums":[5,25,625,2,4]},"expected":3,"description":"Choose the longer of two chains."},{"id":"h1","input":{"nums":[100000,99999]},"expected":-1,"description":"Large values with no possible continuation."},{"id":"h2","input":{"nums":[2,4,16,3,9,81,6561]},"expected":4,"description":"Later chain is longer than the early chain."},{"id":"h3","input":{"nums":[2,2,4,4,16]},"expected":3,"description":"Duplicate values should not inflate the streak length."},{"id":"h4","input":{"nums":[3,9,81,6561]},"expected":4,"description":"A clean four-step square chain."},{"id":"h5","input":{"nums":[2,3,4,9,16,25]},"expected":3,"description":"Two candidate chains where the longer one wins."},{"id":"base-ten-square-chain","input":{"nums":[10,100,10000,3,9]},"expected":3,"description":"A non-power-of-two base can still form the longest square chain."},{"id":"tied-three-step-chains","input":{"nums":[6,36,1296,7,49,2401]},"expected":3,"description":"Two separate square streaks tie for the best valid length."}],"hints":[{"level":1,"content":"The original order does not matter. You only need fast answers to \"is this value present?\"","revealPattern":false},{"level":2,"content":"Convert `nums` to a set, then walk from each chain start by repeatedly squaring the current value.","revealPattern":true},{"level":3,"content":"Skip a value if its square root is also present; that value belongs to a chain that starts earlier.","revealPattern":true}],"guidedFlow":{"version":2,"progressRevision":"longest-square-streak-2026-07-19-set-state-definition","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":"nested-scan","name":"Rescan the array for each square","summary":"For each value, walk the whole array to find its square, then walk again for that square's square.","decisionReason":"Every step of every chain rescans the array, so finding one square costs a full pass and the work grows with n times the array length.","complexity":{"time":"O(n^2)","space":"O(1)"},"tradeoffs":["Runs in O(n^2) time and uses O(1) space."],"isOptimal":false},{"id":"set-chain","name":"Set membership chain walk","summary":"Store all values in a set, then follow squared values from each start while each one is present.","decisionReason":"The set answers each \"is the square here?\" in constant time, so a single squared lookup replaces the full array scan that the brute force pays at every step.","complexity":{"time":"O(n log log M)","space":"O(n)"},"tradeoffs":["Runs in O(n log log M) time and uses O(n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"convert-to-set","title":"Build a membership set","description":"Convert the input values into a set for constant average-time lookups.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"initializes_set_state","scope":"convert-to-set","readMode":"set-membership-value-query-v1"}]},"commonMistakes":["Keeping only the array and rescanning it","Using duplicates as separate chain steps"],"hint":"The chain is about values, not positions.","semanticSpec":{"intent":"Create reusable set-membership state from the input.","doneWhen":"The input values are available through a set-like membership structure.","shouldFailWhen":"This step should fail if the solution has no set-like membership state.","roles":["input values","membership set"],"mustProve":["The solution initializes set state from the input."],"mustNotAccept":["Repeated linear membership scans over the raw array."]}},{"id":"skip-non-starts","title":"Skip values with a predecessor","description":"If the integer square root of a value is also present, skip this value because its chain starts earlier.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"checks_set_membership","scope":"membership-check","readMode":"set-membership-value-query-v1"}]},"commonMistakes":["Starting from every value and doing duplicate work","Skipping any value with a non-integer square root"],"hint":"Only skip when `root * root == num` and `root` is present.","semanticSpec":{"intent":"Use membership to identify chain roots.","doneWhen":"The solution performs a set membership check before choosing whether to grow a chain.","shouldFailWhen":"This step should fail if the solution never checks membership before chain growth.","roles":["candidate value","integer square root","membership set"],"mustProve":["A set membership check controls whether a candidate is treated as a start."],"mustNotAccept":["Growing every candidate without any membership guard."]}},{"id":"grow-square-chain","title":"Follow squared values","description":"Repeatedly square the current value while the square exists in the set.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"workflow","readMode":"legacy-fact-query-v1"}]},"commonMistakes":["Adding the current value instead of squaring it","Stopping before checking the next squared value"],"hint":"The loop continues only while the next squared value is present.","semanticSpec":{"intent":"Drive the chain walk with set membership.","doneWhen":"The solution uses a set-membership workflow to continue or stop the square chain.","shouldFailWhen":"This step should fail if membership state is not part of the chain workflow.","roles":["current chain value","next square","membership set"],"mustProve":["The square-chain logic is backed by reusable set-membership state."],"mustNotAccept":["A fixed-length loop that ignores membership."]}},{"id":"track-best","title":"Track the best valid streak","description":"Update the best answer only after a chain reaches length at least two.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"updates_numeric_extremum_state","scope":"track-best","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Returning 1 when no square pair exists","Overwriting the best length with the last chain length"],"hint":"Only lengths greater than one are valid answers.","semanticSpec":{"intent":"Maintain the maximum valid chain length.","doneWhen":"The solution updates an extremum-style numeric answer from computed chain lengths.","shouldFailWhen":"This step should fail if the best length is not updated from chain lengths.","roles":["current length","best length"],"mustProve":["The answer is updated as a numeric extremum."],"mustNotAccept":["Returning the last chain length without comparing."]}},{"id":"return-answer","title":"Return the final answer","description":"Return the best valid streak length, or -1 if none was found.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_terminal_accumulator","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Returning the current chain length","Returning 1 for arrays with no valid streak"],"hint":"The initialized sentinel already represents the no-streak answer.","semanticSpec":{"intent":"Return the terminal accumulated answer.","doneWhen":"The final return is the answer accumulator after all candidates have been considered.","shouldFailWhen":"This step should fail if the returned value is not the accumulated answer.","roles":["best length","return value"],"mustProve":["The terminal return uses the accumulated answer."],"mustNotAccept":["Returning the membership set or the current chain value."]}}],"slides":[{"id":"the-task","kind":"info","chapter":"The obvious way","eyebrow":"Read the problem","title":"A chain where each value squares into the next","workspacePanel":"problem","body":["Return the length of the longest run of values where each one is the square of the one before it, or -1 if no such run of two or more exists. The values can sit anywhere in the array, in any order.","The order in the array does not matter, only which values are present. The obvious way to find a chain is to chase each square by hand through the array."]},{"id":"brute-force","kind":"code-trace","chapter":"The obvious way","eyebrow":"The obvious way","title":"Chase each square through the array","summary":"Chasing each square by hand through the array does find the chain, and it gets the answer right. Watch how it locates each next value.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"best = -1\nfor num in nums:\n    length = 1\n    current = num\n    while (current * current) in nums:\n        current = current * current\n        length += 1\n    if length > 1:\n        best = max(best, length)\nreturn best","steps":[{"id":"start-2","title":"Start the chain at 2","codeLine":5,"summary":"From the 2 at index 0, the inner check asks whether 4 is somewhere in nums and scans the array to find out.","state":{"nums":[2,4,16,3,9],"current":0,"labels":{"nums":"nums"}}},{"id":"scan-for-16","title":"Scan the whole array again for 16","codeLine":5,"summary":"4 is found, so current becomes 4 and the check asks for 16. Finding it means another walk across nums from the start.","state":{"nums":[2,4,16,3,9],"current":1,"labels":{"nums":"nums"}}},{"id":"chain-ends","title":"256 is nowhere, so this chain is length 3","codeLine":5,"summary":"current is 16 and the check asks for 256. The scan walks the entire array, finds nothing, and the chain 2 -> 4 -> 16 ends at length 3.","state":{"nums":[2,4,16,3,9],"current":2,"labels":{"nums":"nums"}}},{"id":"restart-from-4","title":"Then start over from 4","codeLine":2,"summary":"The outer loop moves to the 4 at index 1 and scans the array all over again for 16, 256, and so on, repeating work the 2 chain already did.","state":{"nums":[2,4,16,3,9],"current":1,"labels":{"nums":"nums"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let best = -1;\nfor (const num of nums) {\n    let length = 1;\n    let current = num;\n    while (nums.includes((current * current))) {\n        current = current * current;\n        length++;\n    }\n    if (length > 1) {\n        best = Math.max(best, length);\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":13},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":12}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let best = -1;\nfor (const num of nums) {\n    let length = 1;\n    let current = num;\n    while (nums.includes((current * current))) {\n        current = current * current;\n        length++;\n    }\n    if (length > 1) {\n        best = Math.max(best, length);\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":13},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":12}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int best = -1;\nfor (Integer num : nums) {\n    int length = 1;\n    int current = num;\n    while (nums.contains(current * current)) {\n        current = current * current;\n        length++;\n    }\n    if (length > 1) {\n        best = Math.max(best, length);\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":13},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":12}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int best = -1;\nforeach (int num in nums) {\n    int length = 1;\n    int current = num;\n    while (nums.Contains(current * current)) {\n        current = current * current;\n        length++;\n    }\n    if (length > 1) {\n        best = Math.Max(best, length);\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":13},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":12}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int best = -1;\nfor (int num : nums) {\n    int length = 1;\n    int current = num;\n    while (containsValue(nums, (current * current))) {\n        current = current * current;\n        length++;\n    }\n    if (length > 1) {\n        best = max(best, length);\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":13},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":12}}}}}},{"id":"cost-probe","kind":"case-probe","chapter":"The obvious way","eyebrow":"Count the cost","title":"What does one in nums check cost on a large array?","workspacePanel":"visualizer","summary":"Each step of every chain asks whether one squared value is somewhere in nums. With no set, in nums walks the array entry by entry.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"scan-cost","state":{"nums":[2,4,16,3,9],"current":2,"labels":{"nums":"nums (scanning for 16)"}}}]},"options":[{"id":"linear-scan","label":"A full walk of the array, up to n comparisons every time","rationale":"in nums has no shortcut: it compares the squared value against each entry until it finds a match or runs out. With one such check per chain step and a chain step per value, the work grows with n times n.","isCorrect":true},{"id":"constant","label":"A single comparison, because the value is right there","rationale":"The squared value can sit anywhere in the array, so the check has to look through the entries to find it; there is no way to land on it directly.","isCorrect":false},{"id":"log","label":"About log n steps, by halving the array","rationale":"Halving needs sorted order and binary search; nums is unsorted here, so the membership test falls back to a linear walk.","isCorrect":false}],"answer":"Each in nums check walks the array, up to n comparisons, and there is one such check per chain step across all values, so the whole thing grows with n squared. That repeated scanning is what the next idea has to beat."},{"id":"pattern-quiz","kind":"choice","source":"pattern-recognition","chapter":"The idea","eyebrow":"Spot the pattern","title":"Which question, answered instantly, removes the rescan?","workspacePanel":"trace","quiz":{"contract":"pattern-recognition-v1","question":"Which question, answered instantly, removes the rescan?","signalPrompt":"The brute force repeats the same kind of question at every chain step. Which one, if it were free, ends the repeated scanning?","options":[{"id":"is-value-present","label":"Is this exact value present in the input?","signal":"Every chain step asks the same thing: does the squared value exist somewhere in nums?","rationale":"A set answers \"is this value here?\" in constant average time, so each squared value is one lookup instead of a full scan.","isCorrect":true},{"id":"is-sorted","label":"Where does this value fall in sorted order?","signal":"Position in sorted order would enable binary search, but the chain never needs ordering.","rationale":"The chain only cares whether a square exists, not where it ranks; sorting adds a log factor for a question membership already answers.","isCorrect":false},{"id":"largest-so-far","label":"What is the largest value seen so far?","signal":"A running maximum summarizes the values but not the part the chain needs.","rationale":"Knowing the maximum says nothing about whether one specific square is present.","isCorrect":false},{"id":"how-many-smaller","label":"How many values are smaller than this one?","signal":"A count compresses the input into a number.","rationale":"A count cannot tell you whether the exact squared value exists, which is the only thing the chain check asks.","isCorrect":false}],"missFeedback":"The repeated work is a membership question about one exact value: is the square present? The state has to answer that directly."}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"nums":[2,4,16,3,9],"current":0,"seenSet":[2,3,4,9,16],"seenHighlight":4,"labels":{"nums":"nums","seen":"values"}}}]},"selection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"nested-scan","name":"Rescan the array for each square","summary":"For each value, walk the whole array to find its square, then walk again for that square's square.","decisionReason":"Every step of every chain rescans the array, so finding one square costs a full pass and the work grows with n times the array length.","complexity":{"time":"O(n^2)","space":"O(1)"},"tradeoffs":["Runs in O(n^2) time and uses O(1) space."],"isOptimal":false},{"id":"set-chain","name":"Set membership chain walk","summary":"Store all values in a set, then follow squared values from each start while each one is present.","decisionReason":"The set answers each \"is the square here?\" in constant time, so a single squared lookup replaces the full array scan that the brute force pays at every step.","complexity":{"time":"O(n log log M)","space":"O(n)"},"tradeoffs":["Runs in O(n log log M) time and uses O(n) space."],"isOptimal":true}]}},{"id":"set-meaning","chapter":"The idea","kind":"case-probe","eyebrow":"Define the state","title":"What should the set contain?","summary":"A chain step only needs to answer whether a particular squared value exists somewhere in nums.","workspacePanel":"visualizer","options":[{"id":"distinct-input-values","label":"Every distinct value present in the input","rationale":"Then each square lookup answers the exact existence question in constant average time, and duplicate copies do not create extra chain steps.","isCorrect":true},{"id":"current-chain","label":"Only values already counted in the current chain","rationale":"That records the past but cannot answer whether the next square exists ahead. The set needs the full input membership before any chain walk starts."},{"id":"visited-starts","label":"Only values whose chains have already been explored","rationale":"Exploration history does not answer whether a candidate square is available. Membership of all input values is the reusable state."}],"answer":"Store every distinct input value. The set represents value existence, so a chain can test its next square without scanning nums again.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"set-meaning-state","state":{"nums":[2,4,16,3,9],"seenSet":[2,3,4,9,16],"labels":{"nums":"nums","seen":"values"}}}]}},{"id":"root-probe","kind":"case-probe","chapter":"The idea","eyebrow":"Find the waste","title":"Starting from the 4, what chain do you count?","workspacePanel":"visualizer","summary":"The values are {2, 3, 4, 9, 16}, and the outer loop is considering 4.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"root-state","state":{"nums":[2,4,16,3,9],"current":1,"seenSet":[2,3,4,9,16],"seenHighlight":2,"labels":{"nums":"nums","seen":"values"}}}]},"options":[{"id":"suffix","label":"4 -> 16, a length-2 suffix of the chain that already started at 2","rationale":"From 4 you reach 16 and stop, counting 2. The full chain 2 -> 4 -> 16 was already counted when the walk began at 2, so this is the same chain measured from the middle.","isCorrect":true},{"id":"full-chain","label":"2 -> 4 -> 16, the full chain of length 3","rationale":"The walk only moves forward by squaring, so from 4 it can reach 16 but never step back to 2. It counts 4 -> 16 and misses the 2.","isCorrect":false},{"id":"nothing","label":"Nothing, because 4 is a perfect square","rationale":"4 squared is 16, which is present, so the walk does grow a chain from 4; the issue is that the chain is a piece of one already counted, not that it is empty.","isCorrect":false}],"answer":"From 4 you only get 4 -> 16, a suffix of the chain that began at 2. The square root of 4 is 2, and 2 is in the set, so 4 is a middle value: its chain was already counted from the start. Skip any value whose square root is present."},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"Start only at roots, then square forward","workspacePanel":"visualizer","body":["Put every value in a set. A value is a chain root only when its square root is not also in the set; from a root, keep squaring while the next square is present, counting the length as you go.","We will run it on nums = [2, 4, 16, 3, 9]. As each beat plays, watch the highlighted lookup and which value the walk is considering, and decide for yourself whether the chain grows, halts, or skips."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"nums":[2,4,16,3,9],"current":0,"seenSet":[2,3,4,9,16],"labels":{"nums":"nums","seen":"values"}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Trace the walk","title":"Trace the chain from its root","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"look-for-4","state":{"nums":[2,4,16,3,9],"current":0,"seenSet":[2,3,4,9,16],"seenHighlight":4,"labels":{"nums":"nums","seen":"values"}}},{"id":"look-for-256","state":{"nums":[2,4,16,3,9],"current":2,"seenSet":[2,3,4,9,16],"seenHighlight":256,"labels":{"nums":"nums","seen":"values"}}},{"id":"skip-16","state":{"nums":[2,4,16,3,9],"current":2,"seenSet":[2,3,4,9,16],"seenHighlight":4,"labels":{"nums":"nums","seen":"values"}}}]},"beats":[{"id":"look-for-4","title":"The walk squares 2 and looks up 4 (highlighted). What happens to length?","summary":"2 is a root because its square root, the integer below it, is not in the set.","prompt":"current is 2, the lookup is 4, and the values are {2, 3, 4, 9, 16}.","options":[{"id":"four","label":"4 is present, so current advances to 4 and length becomes 2","rationale":"2 squared is 4, and 4 is in the set, so current advances to 4 and the chain so far is 2 -> 4.","isCorrect":true},{"id":"stops","label":"The walk stops, because 2 is too small to start a chain","rationale":"A root only needs its own square to be present to grow. 4 is in the set, so the chain does grow rather than stop.","isCorrect":false},{"id":"two","label":"It looks for another 2 to pair the value with itself","rationale":"A streak follows squares of the previous value; from 2 the lookup is 4, and that is what extends the chain.","isCorrect":false}],"answer":"4 is present, so current advances to 4 and the chain grows to 2 -> 4. The length is now 2."},{"id":"look-for-256","title":"current is 16 and the next lookup is 256 (highlighted). What happens to the chain?","summary":"The chain so far is 2 -> 4 -> 16, a length of 3.","prompt":"current is 16, the lookup is 256, and the values are {2, 3, 4, 9, 16}.","options":[{"id":"no-256","label":"256 is not in the set, so the walk halts and the chain stays length 3","rationale":"The loop continues only while the next square is present. 256 is missing, so the chain ends at 16 with a final length of 3.","isCorrect":true},{"id":"too-big","label":"The walk continues anyway, since 16 is still a valid value","rationale":"The walk only continues while the next square is present. 256 is absent, so the membership check fails and the chain halts here.","isCorrect":false},{"id":"length-cap","label":"A length cap of 3 forces the chain to stop","rationale":"There is no length cap. The clean power chain 2 -> 4 -> 16 -> 256 -> 65536 reaches length 5 when those values are present; this one stops only because 256 is missing.","isCorrect":false}],"answer":"256 is not in the set, so the membership check fails and the walk halts. The chain 2 -> 4 -> 16 is length 3, and best becomes 3."},{"id":"skip-16","title":"The outer loop reaches 16, whose square root 4 (highlighted) is present. What happens?","summary":"best is already 3; the values are still {2, 3, 4, 9, 16}.","prompt":"The walk considers starting a new chain at 16, and 4 is in the set.","options":[{"id":"skip","label":"Skip 16: with its square root 4 present, its chain was already counted from 2","rationale":"16 has integer square root 4, and 4 is in the set, so 16 is a middle value. Starting here would only recount 16, a suffix of the chain already measured from 2.","isCorrect":true},{"id":"recount","label":"Start a new chain at 16 and add its length to best","rationale":"That would recount a piece of the 2 -> 4 -> 16 chain. The root check exists precisely to avoid this duplicate work, so 16 is skipped instead.","isCorrect":false},{"id":"reset-best","label":"Reset best, since 16 has no square ahead","rationale":"best only ever grows toward the maximum; a short or absent chain from 16 never lowers it.","isCorrect":false}],"answer":"16 is skipped because its square root 4 is in the set, marking it a middle value. best stays 3, which is the answer for this input."}]},{"id":"single-value-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","title":"Should a lone value count as a streak?","workspacePanel":"trace","summary":"Every walk starts a chain at length 1, even a value with no square ahead. Folding that length straight into the answer looks harmless and passes every input that does have a real chain. Watch what it does on an array where every walk stops immediately.","pitfall":"The code below keeps the root skip but drops the length > 1 guard, feeding every chain length, including a lone 1, into best.","whyItMatters":"On nums = [2, 3, 5] no value has its square present, so the correct answer is -1. Each walk reaches length 1 and stops; without the length > 1 guard, best is raised to 1 and the function returns 1, a streak that does not exist. Keeping the guard means a lone value never counts.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"values = set(nums)\nbest = -1\nfor num in values:\n    root = 1\n    while (root + 1) * (root + 1) <= num:\n        root = root + 1\n    if root * root == num and root in values:\n        continue\n    length = 1\n    current = num\n    while (current * current) in values:\n        current = current * current\n        length += 1\n    best = max(best, length)\nreturn best","steps":[{"id":"lone-2","title":"2 stands alone","codeLine":11,"summary":"2 is a root, so it is not skipped. From 2 the check asks for 4, which is not in {2, 3, 5}. The while loop never runs, so length stays 1.","state":{"nums":[2,3,5],"current":0,"seenSet":[2,3,5],"labels":{"nums":"nums","seen":"values"}}},{"id":"best-becomes-1","title":"A length of 1 is fed into best","codeLine":14,"summary":"With no guard, best = max(-1, 1) becomes 1, recording a streak from a single value that has no square partner.","state":{"nums":[2,3,5],"current":0,"seenSet":[2,3,5],"labels":{"nums":"nums","seen":"values"}}},{"id":"returns-1","title":"1, and wrong","codeLine":15,"summary":"Every value in [2, 3, 5] is a lone 1, so best ends at 1 and the function returns 1. The correct answer is -1: no square streak exists.","state":{"nums":[2,3,5],"current":2,"seenSet":[2,3,5],"labels":{"nums":"nums","seen":"values"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const values = new Set(nums);\nlet best = -1;\nfor (const num of values) {\n    let root = 1;\n    while (((root + 1) * (root + 1)) <= num) {\n        root = root + 1;\n    }\n    if ((root * root) === num && values.has(root)) {\n        continue;\n    }\n    let length = 1;\n    let current = num;\n    while (values.has((current * current))) {\n        current = current * current;\n        length++;\n    }\n    best = Math.max(best, length);\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":8,"8":9,"9":11,"10":12,"11":13,"12":14,"13":15,"14":17,"15":19},"statementBundles":{"6":{"startLine":6,"endLine":7},"8":{"startLine":9,"endLine":10},"13":{"startLine":15,"endLine":16},"14":{"startLine":17,"endLine":18}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const values = new Set(nums);\nlet best = -1;\nfor (const num of values) {\n    let root = 1;\n    while (((root + 1) * (root + 1)) <= num) {\n        root = root + 1;\n    }\n    if ((root * root) === num && values.has(root)) {\n        continue;\n    }\n    let length = 1;\n    let current = num;\n    while (values.has((current * current))) {\n        current = current * current;\n        length++;\n    }\n    best = Math.max(best, length);\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":8,"8":9,"9":11,"10":12,"11":13,"12":14,"13":15,"14":17,"15":19},"statementBundles":{"6":{"startLine":6,"endLine":7},"8":{"startLine":9,"endLine":10},"13":{"startLine":15,"endLine":16},"14":{"startLine":17,"endLine":18}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"Set<Integer> values = new HashSet<Integer>(nums);\nint best = -1;\nfor (Integer num : values) {\n    int root = 1;\n    while (((root + 1) * (root + 1)) <= num) {\n        root = root + 1;\n    }\n    if (((root * root) == num && values.contains(root))) {\n        continue;\n    }\n    int length = 1;\n    int current = num;\n    while (values.contains(current * current)) {\n        current = current * current;\n        length++;\n    }\n    best = Math.max(best, length);\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":8,"8":9,"9":11,"10":12,"11":13,"12":14,"13":15,"14":17,"15":19},"statementBundles":{"6":{"startLine":6,"endLine":7},"8":{"startLine":9,"endLine":10},"13":{"startLine":15,"endLine":16},"14":{"startLine":17,"endLine":18}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"HashSet<int> values = new(nums);\nint best = -1;\nforeach (int num in values) {\n    int root = 1;\n    while ((root + 1) * (root + 1) <= num) {\n        root = root + 1;\n    }\n    if (root * root == num && values.Contains(root)) {\n        continue;\n    }\n    int length = 1;\n    int current = num;\n    while (values.Contains(current * current)) {\n        current = current * current;\n        length++;\n    }\n    best = Math.Max(best, length);\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":8,"8":9,"9":11,"10":12,"11":13,"12":14,"13":15,"14":17,"15":19},"statementBundles":{"6":{"startLine":6,"endLine":7},"8":{"startLine":9,"endLine":10},"13":{"startLine":15,"endLine":16},"14":{"startLine":17,"endLine":18}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"unordered_set<int> values = unordered_set<int>(nums.begin(), nums.end());\nint best = -1;\nfor (int num : values) {\n    int root = 1;\n    while (((root + 1) * (root + 1)) <= num) {\n        root = root + 1;\n    }\n    if (((root * root) == num && values.count(root))) {\n        continue;\n    }\n    int length = 1;\n    int current = num;\n    while (values.count((current * current))) {\n        current = current * current;\n        length++;\n    }\n    best = max(best, length);\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":8,"8":9,"9":11,"10":12,"11":13,"12":14,"13":15,"14":17,"15":19},"statementBundles":{"6":{"startLine":6,"endLine":7},"8":{"startLine":9,"endLine":10},"13":{"startLine":15,"endLine":16},"14":{"startLine":17,"endLine":18}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["The length > 1 guard kept a lone value from counting. Two more inputs press on what the set and the root skip promise.","Worth checking before coding are a value whose floor square root is present but is not its exact root, and an array with repeated values. Each probe ahead works out what the code returns."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"arrays":[{"name":"floor-root case","values":[2,8,64]},{"name":"duplicate case","values":[2,2,4,4,16]}]}}]}},{"id":"no-streak-probe","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"Does the root skip wrongly skip 8 in [2, 8, 64]?","workspacePanel":"visualizer","summary":"nums = [2, 8, 64]. The integer floor of sqrt(8) is 2, and 2 is in the set.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-streak-state","state":{"nums":[2,8,64],"current":1,"seenSet":[2,8,64],"seenHighlight":2,"labels":{"nums":"nums","seen":"values"}}}]},"options":[{"id":"exact-square","label":"No: 8 is kept, because 2 * 2 is 4, not 8, so 2 is not the square root of 8","rationale":"The skip fires only when root * root == num for an integer root that is present. floor(sqrt(8)) is 2, but 2 * 2 is 4, so the exact-square test fails and 8 is treated as a chain root, giving 8 -> 64 of length 2.","isCorrect":true},{"id":"floor-skip","label":"Yes: floor(sqrt(8)) is 2 and 2 is present, so 8 is skipped","rationale":"Skipping on the floor alone would drop a real root. The guard must also verify root * root == num; since 2 * 2 is 4, not 8, 8 is not skipped and its chain is counted.","isCorrect":false},{"id":"skip-loses-chain","label":"Yes, and the answer becomes -1 because the chain is lost","rationale":"If 8 were skipped the chain would vanish, but the exact-square check prevents that. With 8 kept, 8 -> 64 is found and the answer is 2.","isCorrect":false}],"answer":"No. The skip requires root * root == num for a present integer root. floor(sqrt(8)) is 2, but 2 * 2 is 4, so 8 is not a perfect square and stays a valid root. The walk counts 8 -> 64 for length 2. Only skip when the squared root lands exactly on the value."},{"id":"duplicates-probe","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"Do repeated values lengthen the chain?","workspacePanel":"visualizer","summary":"nums = [2, 2, 4, 4, 16] has the 2 and the 4 twice each.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"duplicates-state","state":{"nums":[2,2,4,4,16],"current":0,"seenSet":[2,4,16],"seenHighlight":4,"labels":{"nums":"nums","seen":"values"}}}]},"options":[{"id":"no-inflate","label":"No: the set keeps one copy of each value, so the chain is still 2 -> 4 -> 16","rationale":"Building the set collapses the two 2s and two 4s into single entries. The walk asks only whether each square is present, so duplicates change nothing and the length is 3.","isCorrect":true},{"id":"counts-copies","label":"Yes: each repeated value adds a step, giving length 5","rationale":"A streak counts distinct squaring steps, not occurrences. Membership, not how many times a value appears, decides the chain, and the set holds each value once.","isCorrect":false},{"id":"needs-dedup","label":"Only if you add a separate step to remove duplicates first","rationale":"No separate dedup pass is needed: constructing the set from nums already discards repeats, so the same walk handles duplicate input directly.","isCorrect":false}],"answer":"No. The set holds 2, 4, and 16 once each, so the walk counts 2 -> 4 -> 16 for a length of 3. Membership, not occurrence count, defines the chain, which is why a set handles duplicates for free."},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Two things to keep straight: only roots start a chain, and only lengths past one count.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["Build the set of values. For each value, skip it when its square root is already present, since it is a middle of an earlier chain. From a root, keep squaring while the next square is in the set, counting the length. Record the length only once it passes one, and return -1 if nothing ever did."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"nums":[2,4,16,3,9],"seenSet":[2,3,4,9,16],"labels":{"nums":"nums","seen":"values"}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","eyebrow":"Code the rule","title":"Build the set membership chain walk","summary":"Now build it: put the values in a set, skip any value whose square root is already present, then from each root keep squaring while the next square is in the set, track the longest length past one, and return that best length or -1.","workspacePanel":"code"},{"id":"complete","kind":"complete","chapter":"Code","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","summary":"Order does not matter when the question is only whether a value exists; a set turns that question into one lookup.","body":["The chain lives in the values, not their positions, so a set is the right memory: it answers \"is the square here?\" in constant time and the brute force's repeated scans disappear.","Two guards keep the count honest. Starting only at roots avoids recounting suffixes of a chain, and the length > 1 rule keeps a lone value from passing as a streak."],"takeaways":[{"title":"Membership replaces rescanning","body":"Storing the values in a set makes each \"is the square present?\" check a single lookup, turning the O(n^2) chase into one pass plus the chain lengths."},{"title":"Start only at roots","body":"Skipping a value whose square root is present means each chain is counted once, from its earliest value, instead of once per middle."},{"title":"A streak needs two","body":"Counting a length only when it passes one, and seeding the answer at -1, returns -1 exactly when no chain of two or more exists."},{"title":"The final cost","body":"Building the set costs O(n) space, and because each root walks only repeated squares, the values it visits drop off fast: the runtime is O(n log log M) in the max value M, down from the brute force's repeated O(n) rescans."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
