{"id":"longest-increasing-subsequence","title":"Longest Increasing Subsequence","difficulty":"medium","patterns":["dp-1d"],"primaryConcept":"dp-1d-decision","concepts":["dp-1d-decision"],"problemForm":"core","companies":[],"category":"dynamic-programming","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"nums","sizeMetric":"length"},"description":"Given an integer array `nums`, return the length of the longest strictly increasing subsequence.\n\nA subsequence keeps the original order but may delete any number of elements. The chosen values must be strictly increasing.","examples":[{"input":"nums = [10,9,2,5,3,7,101,18]","output":"4","explanation":"One longest increasing subsequence is [2,3,7,101]."},{"input":"nums = [0,1,0,3,2,3]","output":"4","explanation":"One longest increasing subsequence is [0,1,2,3]."},{"input":"nums = [7,7,7,7]","output":"1","explanation":"Equal values do not count as increasing, so any single element is the best subsequence."}],"constraints":[{"id":"1-len-nums-2500","text":"1 <= len(nums) <= 2500","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":2500}},{"id":"10-4-nums-i-10-4","text":"-10^4 <= nums[i] <= 10^4","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":-10000,"max":10000}},{"id":"the-subsequence-must-be-strictly-increasing","text":"The subsequence must be strictly increasing"}],"starterCode":"class Solution:\n    def lengthOfLIS(self, nums: list[int]) -> int:\n        # Your code here\n        pass","functionName":"lengthOfLIS","testCases":[{"id":"1","input":{"nums":[10,9,2,5,3,7,101,18]},"expected":4,"description":"Canonical mixed sequence."},{"id":"2","input":{"nums":[0,1,0,3,2,3]},"expected":4,"description":"Best subsequence skips several elements."},{"id":"3","input":{"nums":[7,7,7,7]},"expected":1,"description":"Equal values are not strictly increasing."},{"id":"4","input":{"nums":[4,10,4,3,8,9]},"expected":3,"description":"Best subsequence can start after earlier large values."},{"id":"5","input":{"nums":[5,4,3,2,1]},"expected":1,"description":"Strictly decreasing input."},{"id":"6","input":{"nums":[1]},"expected":1,"description":"Single element."},{"id":"h1","input":{"nums":[2,2,2,2]},"expected":1},{"id":"h2","input":{"nums":[1,2,4,3,5,4,7,2]},"expected":5},{"id":"h3","input":{"nums":[0,-1,2,3,-2,4,5]},"expected":5},{"id":"h4","input":{"nums":[10,20,10,30,20,50]},"expected":4},{"id":"negative-to-positive-with-branch","input":{"nums":[-2,-1,0,3,2,3]},"expected":5,"description":"A later smaller value can extend the best negative-to-positive chain."},{"id":"late-rise-after-reset","input":{"nums":[9,1,3,7,5,6,20]},"expected":5,"description":"The best subsequence starts after an early high value and skips a dip."}],"hints":[{"level":1,"content":"For each index, ask what the best increasing subsequence ending exactly at that index could be.","revealPattern":false},{"level":2,"content":"Compare the current value with every earlier value. If `nums[j] < nums[i]`, then a subsequence ending at `j` can extend to `i`.","revealPattern":true},{"level":3,"content":"Initialize every `dp[i]` to `1`, because each value is a length-1 subsequence by itself.","revealPattern":true}],"guidedFlow":{"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement first?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"all-subsequences","name":"Enumerate subsequences","summary":"Try every include-or-skip combination and keep the longest increasing one.","decisionReason":"It checks every one of the two-to-the-n subsequences, re-deciding the same tails over and over.","complexity":{"time":"O(2^n)","space":"O(n)"},"tradeoffs":["Runs in O(2^n) time and uses O(n) space."],"isOptimal":false},{"id":"dp-table","name":"DP table by ending index","summary":"For each index, scan earlier indices and extend compatible subsequences.","decisionReason":"For each number, record the longest run that ends on it by extending the best earlier run it can follow, so every position is solved once.","complexity":{"time":"O(n^2)","space":"O(n)"},"tradeoffs":["Runs in O(n^2) time and uses O(n) space."],"isOptimal":true},{"id":"tails-binary-search","name":"Tails with binary search","summary":"Maintain minimal possible tails for each length.","decisionReason":"The tails array returns the same LIS length in O(n log n) time. The guided implementation uses dp[i] so every earlier value that can extend into nums[i] remains visible while the recurrence is built.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Runs in O(n log n) time and uses O(n) space."],"isViable":true,"isOptimal":false}]},"codingCheckpoints":[{"id":"seed-length-one","title":"Seed every state to length one","description":"Create a dp array where each position starts at 1.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_recurrence_state","readMode":"legacy-fact-query-v1"}]},"semanticSpec":{"intent":"Create an indexed recurrence state where every position starts as a length-one subsequence.","doneWhen":"The DP state is initialized before scanning transitions.","shouldFailWhen":"The recurrence scan starts without a seeded state for each index.","roles":["indexed DP state","base subsequence length"],"mustProve":["recurrence state initialization"],"mustNotAccept":["unseeded recurrence state"]},"commonMistakes":["Initializing states to 0","Forgetting that each element alone is valid"],"hint":"Every value can form a subsequence by itself."},{"id":"scan-current-index","title":"Scan each current index","description":"Loop over every possible ending index i.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_indexed_state_space","scope":"outer-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Scan each indexed DP state as a possible subsequence ending position.","doneWhen":"A loop traverses the indexed state space by current index.","shouldFailWhen":"The code seeds DP but never scans current ending indices.","roles":["current index","indexed DP state"],"mustProve":["indexed state-space scan"],"mustNotAccept":["state initialization without a scan"]},"commonMistakes":["Skipping index 0 without preserving its base value","Stopping before the last index"],"hint":"Each position needs a final best ending-at-that-position value."},{"id":"scan-previous-indices","title":"Scan earlier candidates","description":"For each i, scan all j values before i.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_nested_choice_state_space","scope":"inner-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"For each current index, scan earlier candidate predecessor indices.","doneWhen":"A nested loop visits prior indices for the current ending index.","shouldFailWhen":"The code only checks the current index or the immediate previous index.","roles":["current index","previous index","indexed DP state"],"mustProve":["nested choice state-space scan"],"mustNotAccept":["single-index scan without predecessor choices"]},"commonMistakes":["Looking at future indices","Only checking the immediate previous value"],"hint":"The previous element in the subsequence can be any earlier index."},{"id":"check-increasing","title":"Require a strict increase","description":"Only extend from j to i when nums[j] < nums[i].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"guards_indexed_transition_by_input_fit","scope":"check-condition","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Guard predecessor extension with the input-value comparison that makes the subsequence strictly increasing.","doneWhen":"The predecessor branch checks that the earlier value is less than the current value.","shouldFailWhen":"The code extends predecessors without comparing input values or accepts equal values.","roles":["current input value","previous input value","guarded transition"],"mustProve":["input-fit guard for indexed transition"],"mustNotAccept":["unguarded predecessor transition"]},"commonMistakes":["Using <= and allowing equal values","Comparing indices instead of values"],"hint":"A later index can extend only when its value is larger than the earlier value."},{"id":"extend-best","title":"Extend the best compatible state","description":"Update dp[i] with max(dp[i], dp[j] + 1) when j can precede i.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"computes_recurrence_transition","scope":"compute-next-states","readMode":"dp-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_recurrence_state","scope":"extend-best","readMode":"dp-value-query-v1"}]}]},"semanticSpec":{"intent":"Compute and write the best recurrence value for the current ending index.","doneWhen":"A guarded predecessor contributes dp[j] + 1 and the result is written back to dp[i] with an extremum update.","shouldFailWhen":"The code scans compatible predecessors but never updates the indexed DP state.","roles":["current DP state","predecessor DP state","recurrence write"],"mustProve":["recurrence transition computation","recurrence state writeback"],"mustNotAccept":["guarded scan without DP write"],"proofSnippets":[{"id":"py-extend-best","language":"python","code":"def lengthOfLIS(nums):\n    dp = [1] * len(nums)\n    for i in range(len(nums)):\n        for j in range(i):\n            if nums[j] < nums[i]:\n                dp[i] = max(dp[i], dp[j] + 1)"}]},"commonMistakes":["Overwriting dp[i] with the last compatible candidate","Adding nums[i] instead of adding one to the length"],"hint":"The state stores a length, so extension adds 1."},{"id":"return-best-length","title":"Return the best length","description":"Return the maximum length across all ending positions.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]},"semanticSpec":{"intent":"Return the terminal numeric length after all ending positions have been considered.","doneWhen":"The function returns the tracked best numeric length after the DP scan.","shouldFailWhen":"The function returns a local DP cell, the DP array, or the subsequence values.","roles":["terminal numeric result","indexed DP state"],"mustProve":["terminal numeric state return"],"mustNotAccept":["returning a collection instead of a length"],"proofSnippets":[{"id":"py-return-best-length","language":"python","code":"def lengthOfLIS(nums):\n    dp = [1] * len(nums)\n    best = 1\n    for i in range(len(nums)):\n        for j in range(i):\n            if nums[j] < nums[i]:\n                dp[i] = max(dp[i], dp[j] + 1)\n        best = max(best, dp[i])\n    return best"}]},"commonMistakes":["Returning dp[-1] even when the best subsequence ends earlier","Returning the subsequence values instead of its length"],"hint":"The answer may end at any index."}],"version":2,"progressRevision":"longest-increasing-subsequence-2026-07-19-ending-state-bridge","slides":[{"id":"read-the-signal","chapter":"The numbers","kind":"info","eyebrow":"Read the problem","title":"The longest climbing run","workspacePanel":"problem","body":["You get a list of numbers. Find the length of the longest subsequence whose values strictly increase. The chosen numbers keep their order but need not be next to each other.","Each value can be kept or skipped. Listing every possible subsequence gets the answer, but the number of candidates doubles with every element."]},{"id":"enumerate-candidates","chapter":"The obvious way","kind":"info","eyebrow":"Name the repeated choice","title":"Keep or skip builds too many candidates","workspacePanel":"visualizer","body":["An exhaustive search branches at every number: keep it when it stays increasing, or skip it. Before reaching 7 in [2, 5, 3, 7, 4], that search has already produced [5] and [2, 5], both ending at the same 5, along with [3] and [2, 3], both ending at the same 3.","The next number only asks whether it is larger than a candidate's final value. That makes candidates ending at the same position directly comparable."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"candidate-groups","state":{"rows":[{"label":"end at 5","values":[5,"2,5"]},{"label":"end at 3","values":[3,"2,3"]}]}}]}},{"id":"compress-ending-state","chapter":"The idea","kind":"case-probe","eyebrow":"Compress the candidates","title":"Two increasing subsequences end at the same number. Which one can we discard?","summary":"[5] and [2, 5] both end at the 5 at index 1. Any later value sees the same final value in either case.","workspacePanel":"visualizer","options":[{"id":"discard-shorter","label":"Discard [5]; [2, 5] is longer and can extend to every later value that [5] can","rationale":"Both candidates have the same final value, so they have exactly the same future options. Keeping only the longer length loses no possible answer.","isCorrect":true},{"id":"discard-longer","label":"Discard [2, 5], because it used more earlier numbers","rationale":"Using more earlier numbers is the goal, and it does not restrict the future because both candidates end at the same 5."},{"id":"keep-both","label":"Keep both, because their earlier choices are different","rationale":"Those earlier choices no longer affect compatibility. A later number only needs the shared final value 5, so the shorter candidate can never beat the longer one."}],"answer":"Keep only the longest subsequence ending at each position. Its final value is nums[i], and its length is the one number dp[i] must remember.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"same-ending-value","state":{"rows":[{"label":"shorter","values":[5]},{"label":"longer","values":[2,5]}],"current":5}}]}},{"id":"ending-here","chapter":"The idea","kind":"case-probe","eyebrow":"Build the rule","title":"Which earlier run can the current number build on?","summary":"nums = [2, 5, 3, 7, 4], at the 7 (index 3). The dp row so far is [1, 2, 2, ?, ?].","workspacePanel":"visualizer","options":[{"id":"smaller-earlier","label":"The best run ending on any earlier number smaller than this one, plus this number","rationale":"This number can follow any earlier number below it. Taking the longest such run and adding one gives the longest run ending here.","isCorrect":true},{"id":"previous-only","label":"The run ending on the number just before it","rationale":"The previous number may be larger, which this one cannot follow. Every earlier smaller number is a candidate, not only the immediate neighbor.","isCorrect":false},{"id":"global-best","label":"The longest run found anywhere so far, plus this number","rationale":"That run might end on a number larger than this one, which this number cannot extend. Only runs ending below it can be continued.","isCorrect":false}],"answer":"The best run ending on an earlier smaller number, plus one. So the length here is 1 plus the largest dp value among earlier numbers below it.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ending-here-state","state":{"rows":[{"label":"nums","values":[2,5,3,7,4]},{"label":"dp","values":[1,2,2,1,1],"changed":[]}],"i":3}}]}},{"id":"base-case","chapter":"The idea","kind":"case-probe","eyebrow":"Set the floor","title":"What if no earlier number is smaller?","summary":"A number has no smaller number anywhere before it.","workspacePanel":"visualizer","options":[{"id":"one","label":"Its longest run is just 1, itself","rationale":"A single number is an increasing run of length 1. With nothing smaller to follow, that is the best it can do, so every dp value starts at 1.","isCorrect":true},{"id":"zero","label":"0, since it extends nothing","rationale":"The number still counts as a run on its own. The shortest increasing run is one number, not zero.","isCorrect":false},{"id":"skip","label":"It is skipped and has no value","rationale":"Every number gets a length, because every number is at least a run of one. None are skipped in the table.","isCorrect":false}],"answer":"1. A number with nothing smaller before it is a run of length 1 by itself, which is why the whole dp table starts at 1.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"base-case-state","state":{"rows":[{"label":"nums","values":[2,5,3,7,4]},{"label":"dp","values":[1,1,1,1,1],"changed":[]}],"i":0}}]}},{"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":"approach-structure","state":{"rows":[{"label":"nums","values":[2,5,3,7,4]},{"label":"dp","values":[1,1,1,1,1],"changed":[]}],"i":0}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"A length under every number","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"rows":[{"label":"nums","values":[2,5,3,7,4]},{"label":"dp","values":[1,1,1,1,1],"changed":[]}],"i":0}}]},"body":["The dp row sits under the numbers, one cell each, every cell starting at 1.","For each number left to right, look back at every smaller earlier number and take the largest dp there, then set this cell to one more than it.","The answer is the largest value anywhere in the dp row, since the longest run can end on any number."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the table","title":"Trace the lengths","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"at-five","state":{"rows":[{"label":"nums","values":[2,5,3,7,4]},{"label":"dp","values":[1,2,1,1,1],"changed":[1]}],"i":1}},{"id":"at-seven","state":{"rows":[{"label":"nums","values":[2,5,3,7,4]},{"label":"dp","values":[1,2,2,3,1],"changed":[3]}],"i":3}},{"id":"answer","state":{"rows":[{"label":"nums","values":[2,5,3,7,4]},{"label":"dp","values":[1,2,2,3,3],"changed":[]}],"i":4}}]},"beats":[{"id":"at-five","title":"At the 5 (index 1), what is its dp value?","summary":"Before it sits only the 2, with dp 1.","prompt":"The number is 5; the only earlier number is 2.","options":[{"id":"two","label":"2","rationale":"5 is larger than the earlier 2, whose dp is 1, so the run 2, 5 has length 1 + 1 = 2.","isCorrect":true},{"id":"one","label":"1","rationale":"It can follow the 2, so it extends that run. 1 + the 2 dp of 1 gives 2.","isCorrect":false},{"id":"three","label":"3","rationale":"Only one earlier number is smaller, the 2 with dp 1. The best is 1 + 1 = 2.","isCorrect":false}],"answer":"2. The 5 follows the earlier 2 (dp 1), so its dp is 1 + 1 = 2."},{"id":"at-seven","title":"At the 7 (index 3), which earlier number does it best follow?","summary":"The current number is 7.","prompt":"The dp row so far is [1, 2, 2] under 2, 5, 3.","options":[{"id":"three","label":"The 5 or the 3, for a dp of 3","rationale":"7 can follow any of them, so it takes the largest earlier dp, which is 2 (the 5 or the 3), and adds one: 3.","isCorrect":true},{"id":"two","label":"The 2, for a dp of 2","rationale":"The 2 has dp 1, but the 5 and 3 have dp 2, both still below 7. Following one of those gives the longer run.","isCorrect":false},{"id":"four","label":"All three at once, for a dp of 4","rationale":"A run follows one earlier number, not all of them. The best single choice has dp 2, so 7 gets 3.","isCorrect":false}],"answer":"3. The largest earlier dp among smaller numbers is 2 (the 5 or the 3), so the 7 gets 1 + 2 = 3."},{"id":"answer","title":"The dp row is [1, 2, 2, 3, 3]. What is the answer?","summary":"The last number, 4, ended with dp 3 as well.","prompt":"The table is filled.","options":[{"id":"max","label":"3, the largest value in the row","rationale":"The longest run can end anywhere, so the answer is the maximum dp, which is 3, from the run ending on 7 (and also on 4).","isCorrect":true},{"id":"last","label":"Whatever the last cell holds","rationale":"Here the last cell also holds 3. On other inputs the longest run can end earlier, so read the maximum dp across the row.","isCorrect":false},{"id":"sum","label":"The sum of the row","rationale":"The cells are lengths of different runs, not pieces to add. The answer is the single largest one.","isCorrect":false}],"answer":"3, the largest dp value. The longest increasing run has length 3."}]},{"id":"last-cell-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Is the answer just the dp of the last number?","summary":"The dp table is built left to right, so the last cell feels like the finish line, and on many inputs it does hold the largest value. Watch a list that ends on a dip.","workspacePanel":"trace","pitfall":"The code below returns the dp value of the last number instead of the largest dp anywhere.","whyItMatters":"The longest run can end on any number, not necessarily the last one. A small final number gets a small dp even when a long run ended earlier. Return the maximum over the whole dp table.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"dp = [1] * len(nums)\nfor i in range(len(nums)):\n    for j in range(i):\n        if nums[j] < nums[i]:\n            dp[i] = max(dp[i], dp[j] + 1)\nreturn dp[-1]","steps":[{"id":"fills-fine","title":"The table fills correctly","codeLine":5,"summary":"nums = [1, 2, 3, 0]. The dp row becomes [1, 2, 3, 1]: a run of 3 ending on the 3, then a lone 0.","state":{"rows":[{"label":"nums","values":[1,2,3,0]},{"label":"dp","values":[1,2,3,1]}],"i":2}},{"id":"last-is-small","title":"The last cell is only 1","codeLine":1,"summary":"The final number 0 has nothing smaller before it, so its dp is 1. The real longest run, length 3, ended back on the 3.","state":{"rows":[{"label":"nums","values":[1,2,3,0]},{"label":"dp","values":[1,2,3,1],"changed":[3]}],"i":3}},{"id":"wrong-answer","title":"It returns 1","codeLine":6,"summary":"Reading only the last cell returns 1 for a list whose longest increasing run is clearly 3. The maximum of the row was the answer.","state":{"rows":[{"label":"nums","values":[1,2,3,0]},{"label":"dp","values":[1,2,3,1]}],"i":3}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const dp = Array(nums.length).fill(1);\nfor (let i = 0; i < nums.length; i++) {\n    for (let j = 0; j < i; j++) {\n        if (nums[j] < nums[i]) {\n            dp[i] = Math.max(dp[i], (dp[j] + 1));\n        }\n    }\n}\nreturn dp[(dp.length - 1)];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":9},"statementBundles":{"5":{"startLine":5,"endLine":8}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const dp = Array(nums.length).fill(1);\nfor (let i = 0; i < nums.length; i++) {\n    for (let j = 0; j < i; j++) {\n        if (nums[j] < nums[i]) {\n            dp[i] = Math.max(dp[i], (dp[j] + 1));\n        }\n    }\n}\nreturn dp[(dp.length - 1)];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":9},"statementBundles":{"5":{"startLine":5,"endLine":8}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> dp = new ArrayList<>();\nfor (int index = 0; index < nums.size(); index++) {\n    dp.add(1);\n}\nfor (int i = 0; i < nums.size(); i++) {\n    for (int j = 0; j < i; j++) {\n        if (nums.get(j) < nums.get(i)) {\n            dp.set(i, Math.max(dp.get(i), (dp.get(j) + 1)));\n        }\n    }\n}\nreturn dp.get((dp.size() - 1));","lineMap":{"1":1,"2":5,"3":6,"4":7,"5":8,"6":12},"statementBundles":{"1":{"startLine":1,"endLine":4},"5":{"startLine":8,"endLine":11}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> dp = Enumerable.Repeat<int>(1, nums.Count).ToList();\nfor (int i = 0; i < nums.Count; i++) {\n    for (int j = 0; j < i; j++) {\n        if (nums[j] < nums[i]) {\n            dp[i] = Math.Max(dp[i], dp[j] + 1);\n        }\n    }\n}\nreturn dp[dp.Count - 1];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":9},"statementBundles":{"5":{"startLine":5,"endLine":8}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> dp = vector<int>(nums.size(), 1);\nfor (int i = 0; i < nums.size(); i++) {\n    for (int j = 0; j < i; j++) {\n        if (nums[j] < nums[i]) {\n            dp[i] = max(dp[i], (dp[j] + 1));\n        }\n    }\n}\nreturn dp[(dp.size() - 1)];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":9},"statementBundles":{"5":{"startLine":5,"endLine":8}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Giving each number the longest run that ends on it, extended from any smaller number before it, filled the table that holds the answer.","Now stress the rule on two inputs: a list that only ever falls, and a list where every number is identical."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"rows":[{"label":"nums","values":[2,5,3,7,4]},{"label":"dp","values":[1,1,1,1,1],"changed":[]}],"i":0}}]}},{"id":"decreasing-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What if the numbers only decrease?","summary":"nums = [5, 4, 3, 2]. Each later value is smaller than the ones before it.","workspacePanel":"visualizer","options":[{"id":"one","label":"1, since no number can follow another","rationale":"No number is larger than an earlier one, so nothing extends. Every dp stays at its starting 1, and the maximum is 1.","isCorrect":true},{"id":"four","label":"4, the length of the list","rationale":"The whole list decreases, so it is not an increasing run. The longest increasing run is a single number, length 1.","isCorrect":false},{"id":"zero","label":"0","rationale":"Even a falling list has runs of length 1. The answer is 1, not 0.","isCorrect":false}],"answer":"1. Nothing can follow anything, so every dp stays 1 and the longest run is a single number.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"decreasing-state","state":{"rows":[{"label":"nums","values":[5,4,3,2]},{"label":"dp","values":[1,1,1,1]}],"i":3}}]}},{"id":"all-equal-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What if every number is the same?","summary":"nums = [4, 4, 4].","workspacePanel":"visualizer","options":[{"id":"one","label":"1, since equal values do not increase","rationale":"A run must strictly increase, and no 4 is larger than another 4, so none extend. Every dp stays 1 and the maximum is 1.","isCorrect":true},{"id":"three","label":"3, the whole list","rationale":"Equal numbers are not increasing. The longest strictly increasing run among identical values is a single number.","isCorrect":false},{"id":"zero","label":"0","rationale":"Each number is a run of length 1 by itself, so the answer is 1, not 0.","isCorrect":false}],"answer":"1. Equal values never satisfy strictly-increasing, so no dp extends and the longest run is a single number.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-equal-edge-state","state":{"rows":[{"label":"nums","values":[4,4,4]},{"label":"dp","values":[1,1,1]}],"i":2}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"A length per number, then the max","summary":"Return the largest length in the table; the best run may end before the last number.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-to-code-start","state":{"rows":[{"label":"nums","values":[2,5,3,7,4]},{"label":"dp","values":[1,1,1,1,1],"changed":[]}],"i":0}}]},"body":["Start a dp value of 1 under each number. For each number, scan the earlier ones and, for any that is smaller, raise its dp to one more than that earlier dp. Return the largest value in the whole table."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the longest-run table","eyebrow":"Code the rule","summary":"Now write it: seed every cell to 1, then scan each number and look back at the earlier ones; for any that is smaller, take one more than its length and keep the best, then return the largest cell in the table.","workspacePanel":"code","checkpoints":[{"id":"seed-length-one","title":"Seed every state to length one","description":"Create a dp array where each position starts at 1.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_recurrence_state","readMode":"legacy-fact-query-v1"}]},"semanticSpec":{"intent":"Create an indexed recurrence state where every position starts as a length-one subsequence.","doneWhen":"The DP state is initialized before scanning transitions.","shouldFailWhen":"The recurrence scan starts without a seeded state for each index.","roles":["indexed DP state","base subsequence length"],"mustProve":["recurrence state initialization"],"mustNotAccept":["unseeded recurrence state"]},"commonMistakes":["Initializing states to 0","Forgetting that each element alone is valid"],"hint":"Every value can form a subsequence by itself."},{"id":"scan-current-index","title":"Scan each current index","description":"Loop over every possible ending index i.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_indexed_state_space","scope":"outer-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Scan each indexed DP state as a possible subsequence ending position.","doneWhen":"A loop traverses the indexed state space by current index.","shouldFailWhen":"The code seeds DP but never scans current ending indices.","roles":["current index","indexed DP state"],"mustProve":["indexed state-space scan"],"mustNotAccept":["state initialization without a scan"]},"commonMistakes":["Skipping index 0 without preserving its base value","Stopping before the last index"],"hint":"Each position needs a final best ending-at-that-position value."},{"id":"scan-previous-indices","title":"Scan earlier candidates","description":"For each i, scan all j values before i.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_nested_choice_state_space","scope":"inner-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"For each current index, scan earlier candidate predecessor indices.","doneWhen":"A nested loop visits prior indices for the current ending index.","shouldFailWhen":"The code only checks the current index or the immediate previous index.","roles":["current index","previous index","indexed DP state"],"mustProve":["nested choice state-space scan"],"mustNotAccept":["single-index scan without predecessor choices"]},"commonMistakes":["Looking at future indices","Only checking the immediate previous value"],"hint":"The previous element in the subsequence can be any earlier index."},{"id":"check-increasing","title":"Require a strict increase","description":"Only extend from j to i when nums[j] < nums[i].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"guards_indexed_transition_by_input_fit","scope":"check-condition","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Guard predecessor extension with the input-value comparison that makes the subsequence strictly increasing.","doneWhen":"The predecessor branch checks that the earlier value is less than the current value.","shouldFailWhen":"The code extends predecessors without comparing input values or accepts equal values.","roles":["current input value","previous input value","guarded transition"],"mustProve":["input-fit guard for indexed transition"],"mustNotAccept":["unguarded predecessor transition"]},"commonMistakes":["Using <= and allowing equal values","Comparing indices instead of values"],"hint":"A later index can extend only when its value is larger than the earlier value."},{"id":"extend-best","title":"Extend the best compatible state","description":"Update dp[i] with max(dp[i], dp[j] + 1) when j can precede i.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"computes_recurrence_transition","scope":"compute-next-states","readMode":"dp-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_recurrence_state","scope":"extend-best","readMode":"dp-value-query-v1"}]}]},"semanticSpec":{"intent":"Compute and write the best recurrence value for the current ending index.","doneWhen":"A guarded predecessor contributes dp[j] + 1 and the result is written back to dp[i] with an extremum update.","shouldFailWhen":"The code scans compatible predecessors but never updates the indexed DP state.","roles":["current DP state","predecessor DP state","recurrence write"],"mustProve":["recurrence transition computation","recurrence state writeback"],"mustNotAccept":["guarded scan without DP write"],"proofSnippets":[{"id":"py-extend-best","language":"python","code":"def lengthOfLIS(nums):\n    dp = [1] * len(nums)\n    for i in range(len(nums)):\n        for j in range(i):\n            if nums[j] < nums[i]:\n                dp[i] = max(dp[i], dp[j] + 1)"}]},"commonMistakes":["Overwriting dp[i] with the last compatible candidate","Adding nums[i] instead of adding one to the length"],"hint":"The state stores a length, so extension adds 1."},{"id":"return-best-length","title":"Return the best length","description":"Return the maximum length across all ending positions.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]},"semanticSpec":{"intent":"Return the terminal numeric length after all ending positions have been considered.","doneWhen":"The function returns the tracked best numeric length after the DP scan.","shouldFailWhen":"The function returns a local DP cell, the DP array, or the subsequence values.","roles":["terminal numeric result","indexed DP state"],"mustProve":["terminal numeric state return"],"mustNotAccept":["returning a collection instead of a length"],"proofSnippets":[{"id":"py-return-best-length","language":"python","code":"def lengthOfLIS(nums):\n    dp = [1] * len(nums)\n    best = 1\n    for i in range(len(nums)):\n        for j in range(i):\n            if nums[j] < nums[i]:\n                dp[i] = max(dp[i], dp[j] + 1)\n        best = max(best, dp[i])\n    return best"}]},"commonMistakes":["Returning dp[-1] even when the best subsequence ends earlier","Returning the subsequence values instead of its length"],"hint":"The answer may end at any index."}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"The best run ending here extends the best earlier run that ends on a smaller value.","workspacePanel":"code","body":["For each position, the longest increasing run ending there is one more than the best run ending on any earlier, smaller value.","Every position starts as a run of length 1. The answer is the largest value across the table because the best run may end before the last number."],"takeaways":[{"title":"Each end builds on smaller ends","body":"dp[i] = 1 + max(dp[j]) over earlier j with nums[j] < nums[i] turns the whole problem into a scan of earlier answers."},{"title":"The longest run can end anywhere","body":"The answer is the maximum over the whole table, since the best subsequence need not end at the last element."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"executionStyle":"solution-method"}
