{"id":"uncrossed-lines","title":"Uncrossed Lines","difficulty":"medium","patterns":["dp-2d"],"primaryConcept":"dp-2d-strings","concepts":["dp-2d-strings"],"problemForm":"core","companies":["Google","Amazon","Meta","Microsoft"],"category":"dynamic-programming","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"two-arrays","primaryParam":"nums1","secondaryParam":"nums2","sizeMetric":"total-length","sizes":[8,16,32,64],"valueRange":{"min":1,"max":20}},"description":"You are given two integer arrays `nums1` and `nums2`. You may draw connecting lines between equal values, where each line connects one index from `nums1` to one index from `nums2`.\n\nReturn the maximum number of lines you can draw so that no two lines cross.","examples":[{"input":"nums1 = [1,4,2], nums2 = [1,2,4]","output":"2","explanation":"Connect the two 1s and the two 2s. Connecting 4 instead of 2 also gives two lines, but you cannot draw all three without crossing."},{"input":"nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]","output":"3","explanation":"One optimal set connects 5, 1, and 5 in order."}],"constraints":[{"id":"1-len-nums1-len-nums2-500","text":"1 <= len(nums1), len(nums2) <= 500","check":[{"kind":"sizeRange","target":"nums1","measure":"arrayLength","min":1,"max":500},{"kind":"sizeRange","target":"nums2","measure":"arrayLength","min":1,"max":500}]},{"id":"1-nums1-i-nums2-j-2000","text":"1 <= nums1[i], nums2[j] <= 2000","check":[{"kind":"valueRange","target":"nums1","selector":"arrayItems","min":1,"max":2000},{"kind":"valueRange","target":"nums2","selector":"arrayItems","min":1,"max":2000}]}],"starterCode":"class Solution:\n    def maxUncrossedLines(self, nums1: list[int], nums2: list[int]) -> int:\n        # Your code here\n        pass","functionName":"maxUncrossedLines","testCases":[{"id":"1","input":{"nums1":[1,4,2],"nums2":[1,2,4]},"expected":2,"description":"Canonical crossing-choice example."},{"id":"2","input":{"nums1":[2,5,1,2,5],"nums2":[10,5,2,1,5,2]},"expected":3,"description":"Multiple duplicate values with an ordered optimum."},{"id":"3","input":{"nums1":[1,3,7,1,7,5],"nums2":[1,9,2,5,1]},"expected":2,"description":"Best result must preserve order across both arrays."},{"id":"4","input":{"nums1":[1,2,3],"nums2":[4,5,6]},"expected":0,"description":"No equal values means no lines."},{"id":"5","input":{"nums1":[1,1,1],"nums2":[1,1]},"expected":2,"description":"Duplicates can be matched only as many times as the shorter ordered supply allows."},{"id":"6","input":{"nums1":[7],"nums2":[7]},"expected":1,"description":"Single equal values form one line."},{"id":"h1","input":{"nums1":[4],"nums2":[1,2,3]},"expected":0,"description":"A single value with no match draws no lines."},{"id":"h2","input":{"nums1":[1,2,3],"nums2":[1,2,3]},"expected":3,"description":"Identical arrays match every element."},{"id":"h3","input":{"nums1":[1,1,1,1],"nums2":[1,1,1]},"expected":3,"description":"Duplicate values are limited by the shorter array."},{"id":"h4","input":{"nums1":[1,2,3,4],"nums2":[2,4,1,3]},"expected":2,"description":"Crossing choices force the DP to skip bad alignments."},{"id":"topup-staggered-duplicates","input":{"nums1":[1,3,1,3,5],"nums2":[3,1,3,1,5]},"expected":4,"description":"Staggered duplicates force the DP to choose a non-crossing order."},{"id":"topup-long-common-suffix","input":{"nums1":[8,9,1,2,3,4],"nums2":[1,2,3,4,8,9]},"expected":4,"description":"A common suffix beats matching the leading pair."},{"id":"one-value-two-partners","input":{"nums1":[2],"nums2":[2,2]},"expected":1,"description":"The 2 in nums1 matches both values in nums2, but it can carry only one line."}],"hints":[{"level":1,"content":"Two lines cross exactly when the matched values are chosen in different relative orders."},{"level":2,"content":"This is the same ordered-matching recurrence as longest common subsequence, but the sequences contain numbers."},{"level":3,"content":"Let `dp[i][j]` be the best answer using `nums1[0:i]` and `nums2[0:j]`. Equal current values extend the diagonal; different values keep the better top or left answer."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"brute-force-subsequences","name":"Try all subsequences","summary":"Enumerate possible ordered matches and keep the largest non-crossing set.","decisionReason":"It re-explores the same prefix pairs along every branch, so the work doubles with each entry and reaches 2^(m+n).","complexity":{"time":"O(2^(m+n))","space":"O(m+n)"},"tradeoffs":["Runs in O(2^(m+n)) time and uses O(m+n) space."],"isOptimal":false},{"id":"prefix-dp","name":"Prefix DP table","summary":"Build a table where each cell stores the best non-crossing line count for two prefixes.","decisionReason":"Storing one answer per prefix pair solves each subproblem once, collapsing the exponential search into O(m*n).","complexity":{"time":"O(m*n)","space":"O(m*n)"},"tradeoffs":["Runs in O(m*n) time and uses O(m*n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-dp-table","title":"Initialize the prefix DP table","description":"Read both array lengths and create a zero-filled table with one extra row and column.","commonMistakes":["Creating an m x n table instead of an (m+1) x (n+1) table","Using shared inner lists for the rows"],"hint":"Use the extra row and column for empty-prefix states.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_grid_dp_table","scope":"create-dp-table","readMode":"dp-value-query-v1","expected":{"firstAxisInputState":"nums1","secondAxisInputState":"nums2","firstAxisOffset":1,"secondAxisOffset":1}}]},"semanticSpec":{"intent":"Cache both input lengths and allocate a zero-filled (m+1) by (n+1) DP table.","doneWhen":"The implementation stores both lengths and creates an independent-row table where every cell starts at zero.","shouldFailWhen":"The table is the wrong size, rows alias each other, or one input length is not read.","roles":["first array length","second array length","dp table","empty-prefix boundary"],"mustProve":["Both input lengths are read before allocation.","The DP table has one extra row and column.","The table is initialized with zero values."],"mustNotAccept":["An m by n table with no empty-prefix boundary.","A table with aliased rows.","A scalar or one-dimensional state in place of the table."],"equivalentVariants":["Use a nested list comprehension with dimensions m + 1 and n + 1.","Use any equivalent independent-row matrix allocation."],"proofSnippets":[{"id":"py-uncrossed-lines-init-dp-table","language":"python","code":"class Solution:\n    def maxUncrossedLines(self, nums1: list[int], nums2: list[int]) -> int:\n        m = len(nums1)\n        n = len(nums2)\n        dp = [[0] * (n + 1) for _ in range(m + 1)]"}]}},{"id":"nested-loops","title":"Scan every pair of prefixes","description":"Use nested loops over i and j starting at 1 so each real prefix pair is filled once.","commonMistakes":["Starting at 0 and mixing real indices with empty-prefix states","Scanning only one array dimension"],"hint":"Rows represent prefixes of nums1; columns represent prefixes of nums2.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"loops_over_interior_grid","scope":"nested-loops","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Visit every non-empty prefix pair by looping i from 1..m and j from 1..n.","doneWhen":"The implementation has nested loops that cover all interior cells of the DP table.","shouldFailWhen":"Either loop starts from 0, a dimension is missing, or the loops skip valid prefix pairs.","roles":["row prefix index","column prefix index","interior DP cell"],"mustProve":["There is an outer loop over one array's prefixes.","There is an inner loop over the other array's prefixes.","Both loops begin after the empty-prefix boundary."],"mustNotAccept":["A single loop that cannot fill all prefix pairs.","Loops that overwrite the zero base row or column."],"equivalentVariants":["Use `for i in range(1, m + 1)` and `for j in range(1, n + 1)`.","Use equivalent while loops over the same bounds."],"proofSnippets":[{"id":"py-uncrossed-lines-nested-loops","language":"python","code":"class Solution:\n    def maxUncrossedLines(self, nums1: list[int], nums2: list[int]) -> int:\n        m = len(nums1)\n        n = len(nums2)\n        dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n        for i in range(1, m + 1):\n            for j in range(1, n + 1):\n                pass"}]}},{"id":"compare-values","title":"Compare the current values","description":"At each cell, compare nums1[i - 1] and nums2[j - 1] to decide whether a new line can be drawn.","commonMistakes":["Comparing nums1[i] and nums2[j] instead of offset indices","Comparing values from the same array"],"hint":"The DP row and column are one ahead of the actual array indices.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"branches_on_aligned_input_equality","scope":"character-comparison","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Branch on whether the current values from the two arrays are equal.","doneWhen":"The current DP cell uses an equality guard over nums1[i - 1] and nums2[j - 1].","shouldFailWhen":"The code skips the equality guard, uses wrong offsets, or compares an array to itself.","roles":["current nums1 value","current nums2 value","equality guard"],"mustProve":["The guard reads one value from each input array.","Both reads use the prefix-loop indices with a minus-one offset.","The guard separates match and non-match transitions."],"mustNotAccept":["Comparing `nums1[i]` with `nums2[j]`.","Using a one-branch recurrence that ignores value equality."],"equivalentVariants":["Use an equality condition on the aligned current values before updating the DP cell.","Store the two current values in temporaries and compare those temporaries."],"proofSnippets":[{"id":"py-uncrossed-lines-compare-values","language":"python","code":"class Solution:\n    def maxUncrossedLines(self, nums1: list[int], nums2: list[int]) -> int:\n        m = len(nums1)\n        n = len(nums2)\n        dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n        for i in range(1, m + 1):\n            for j in range(1, n + 1):\n                if nums1[i - 1] == nums2[j - 1]:\n                    pass\n                else:\n                    pass"}]}},{"id":"extend-match","title":"Extend a matching line","description":"When the current values match, add one to the diagonal subproblem.","commonMistakes":["Using top or left instead of the diagonal","Forgetting to add one for the new line"],"hint":"A matched pair consumes one value from each array, so it extends dp[i - 1][j - 1].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"extends_diagonal_predecessor","scope":"dp-update-match","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Write dp[i][j] as the diagonal predecessor plus one in the match branch.","doneWhen":"The match branch assigns dp[i][j] = dp[i - 1][j - 1] + 1 or an equivalent expression.","shouldFailWhen":"The update omits the diagonal, omits the plus one, or writes to the wrong cell.","roles":["diagonal predecessor","current DP cell","matched line"],"mustProve":["The update reads dp[i - 1][j - 1].","The update adds one for the current line.","The update targets the current DP cell."],"mustNotAccept":["Using only top or left in the match branch.","Copying the diagonal without adding one."],"equivalentVariants":["Use a temporary for the diagonal value, then assign that value plus one.","Use the direct diagonal-plus-one assignment."],"proofSnippets":[{"id":"py-uncrossed-lines-extend-match","language":"python","code":"class Solution:\n    def maxUncrossedLines(self, nums1: list[int], nums2: list[int]) -> int:\n        m = len(nums1)\n        n = len(nums2)\n        dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n        for i in range(1, m + 1):\n            for j in range(1, n + 1):\n                if nums1[i - 1] == nums2[j - 1]:\n                    dp[i][j] = dp[i - 1][j - 1] + 1\n                else:\n                    pass"}]}},{"id":"keep-best-mismatch","title":"Keep the best mismatch result","description":"When the current values differ, keep the better answer from skipping one value in either array.","commonMistakes":["Taking the minimum instead of the maximum","Reading the diagonal in the mismatch branch"],"hint":"If values differ, a non-crossing optimum either skips nums1[i - 1] or skips nums2[j - 1].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"takes_adjacent_predecessor_extremum","scope":"dp-update-no-match","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Use max(top, left) when the current values cannot be connected.","doneWhen":"The mismatch branch assigns dp[i][j] from the larger of dp[i - 1][j] and dp[i][j - 1].","shouldFailWhen":"The update chooses a smaller value, ignores one adjacent predecessor, or uses an unrelated cell.","roles":["top predecessor","left predecessor","current DP cell","best non-crossing count"],"mustProve":["The mismatch update reads both top and left predecessor cells.","The larger predecessor is stored in the current cell.","The update is used for the non-match branch."],"mustNotAccept":["Using min, addition, or diagonal-only logic for mismatches.","Skipping either top or left predecessor."],"equivalentVariants":["Use `max(dp[i - 1][j], dp[i][j - 1])`.","Use an equivalent conditional that keeps the larger adjacent value."],"proofSnippets":[{"id":"py-uncrossed-lines-keep-best-mismatch","language":"python","code":"class Solution:\n    def maxUncrossedLines(self, nums1: list[int], nums2: list[int]) -> int:\n        m = len(nums1)\n        n = len(nums2)\n        dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n        for i in range(1, m + 1):\n            for j in range(1, n + 1):\n                if nums1[i - 1] == nums2[j - 1]:\n                    dp[i][j] = dp[i - 1][j - 1] + 1\n                else:\n                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])"}]}},{"id":"return-result","title":"Return the completed table result","description":"Return dp[m][n], the best answer using both full arrays.","commonMistakes":["Returning dp[m - 1][n - 1]","Returning the whole table instead of the bottom-right value"],"hint":"The extra row and column mean the full arrays land at dp[m][n].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_bottom_right_cell","scope":"return-answer","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Return the bottom-right DP cell after all prefix pairs are processed.","doneWhen":"The function returns dp[m][n] after the nested loops complete.","shouldFailWhen":"The code returns a partial cell, a stale temporary, or the whole table.","roles":["bottom-right DP cell","full-array answer","returned value"],"mustProve":["The return reads the bottom-right table cell.","The returned cell corresponds to both full input arrays.","The return happens after the recurrence has filled the table."],"mustNotAccept":["Returning dp[m - 1][n - 1].","Returning a row, column, or table object."],"equivalentVariants":["Return `dp[m][n]` directly.","Store `dp[m][n]` in a temporary and return that temporary."],"proofSnippets":[{"id":"py-uncrossed-lines-return-result","language":"python","code":"class Solution:\n    def maxUncrossedLines(self, nums1: list[int], nums2: list[int]) -> int:\n        m = len(nums1)\n        n = len(nums2)\n        dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n        for i in range(1, m + 1):\n            for j in range(1, n + 1):\n                if nums1[i - 1] == nums2[j - 1]:\n                    dp[i][j] = dp[i - 1][j - 1] + 1\n                else:\n                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])\n\n        return dp[m][n]"}]}}],"slides":[{"id":"read-the-signal","kind":"info","chapter":"The lines","eyebrow":"Read the problem","title":"Connect equal values without crossing","workspacePanel":"problem","body":["You are given two integer arrays. Draw a line between an entry in nums1 and an entry in nums2 only when their values are equal, and count the most lines you can draw so that no two lines cross.","The no-crossing rule forces matched values to appear in the same relative order in both arrays. At a mismatch, skipping an entry from either array can lead to a different best result."]},{"id":"brute","kind":"code-trace","chapter":"The obvious way","eyebrow":"The obvious way","title":"Walk both arrays from the front","workspacePanel":"trace","summary":"Compare the arrays from the front, branching whenever the current values differ.","body":["The direct approach walks both arrays from the front. When the current values are equal it draws that line and moves past both. When they differ it cannot tell which side to skip, so it tries skipping each and keeps the longer result."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def max_uncrossed_lines(nums1: list[int], nums2: list[int]) -> int:\n    def lines(i: int, j: int) -> int:\n        if i == len(nums1) or j == len(nums2):\n            return 0\n        if nums1[i] == nums2[j]:\n            return 1 + lines(i + 1, j + 1)\n        return max(lines(i + 1, j), lines(i, j + 1))\n    return lines(0, 0)","steps":[{"id":"brute-match","title":"1 equals 1: draw the line and move both forward","codeLine":6,"summary":"From i = 0, j = 0 the values 1 and 1 are equal, so the answer is 1 plus the best of the rest.","state":{"arrays":[{"name":"nums1","values":[1,4,2],"i":0},{"name":"nums2","values":[1,2,4],"i":0}]}},{"id":"brute-branch","title":"4 vs 2 differ: try skipping each side","codeLine":7,"summary":"From i = 1, j = 1 the values 4 and 2 differ, so the call splits into lines(2, 1) and lines(1, 2) and keeps the larger.","state":{"arrays":[{"name":"nums1","values":[1,4,2],"i":1},{"name":"nums2","values":[1,2,4],"i":1}]}},{"id":"brute-again","title":"Both branches land on i = 2, j = 2","codeLine":7,"summary":"Skipping from nums1 and skipping from nums2 both arrive at i = 2, j = 2, and each one compares 2 against 4 from the start.","state":{"arrays":[{"name":"nums1","values":[1,4,2],"i":2},{"name":"nums2","values":[1,2,4],"i":2}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"function lines(i, j) {\n    if (i == nums1.length || j == nums2.length) {\n        return 0;\n    }\n    if (nums1[i] === nums2[j]) {\n        return (1 + lines((i + 1), (j + 1)));\n    }\n    return Math.max(lines((i + 1), j), lines(i, (j + 1)));\n}\nreturn lines(0, 0);","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"8":10},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"7":{"startLine":8,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"function lines(i: number, j: number): number {\n    if (i == nums1.length || j == nums2.length) {\n        return 0;\n    }\n    if (nums1[i] === nums2[j]) {\n        return (1 + lines((i + 1), (j + 1)));\n    }\n    return Math.max(lines((i + 1), j), lines(i, (j + 1)));\n}\nreturn lines(0, 0);","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"8":10},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"7":{"startLine":8,"endLine":9}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int Lines(int i, int j) {\n    if (i == nums1.Count || j == nums2.Count) {\n        return 0;\n    }\n    if (nums1[i] == nums2[j]) {\n        return 1 + Lines(i + 1, j + 1);\n    }\n    return Math.Max(Lines(i + 1, j), Lines(i, j + 1));\n    return 0;\n}\nreturn Lines(0, 0);","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"8":11},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"7":{"startLine":8,"endLine":10}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<int(int, int)> lines;\n\nlines = [&]( int i, int j ) -> int {\n    if ((i == nums1.size() || j == nums2.size())) {\n        return 0;\n    }\n    if (nums1[i] == nums2[j]) {\n        return (1 + lines((i + 1), (j + 1)));\n    }\n    return max(lines((i + 1), j), lines(i, (j + 1)));\n};\nreturn lines(0, 0);","lineMap":{"3":4,"4":5,"5":7,"6":8,"7":10,"8":12},"statementBundles":{"4":{"startLine":5,"endLine":6},"6":{"startLine":8,"endLine":9},"7":{"startLine":10,"endLine":11}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static int lines(int i, int j, List<Integer> nums1, List<Integer> nums2) {\n    if ((i == nums1.size() || j == nums2.size())) {\n        return 0;\n    }\n    if (nums1.get(i) == nums2.get(j)) {\n        return (1 + lines((i + 1), (j + 1), nums1, nums2));\n    }\n    return Math.max(lines((i + 1), j, nums1, nums2), lines(i, (j + 1), nums1, nums2));\n}\n\nreturn lines(0, 0, nums1, nums2);","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":8,"8":11},"statementBundles":{"4":{"startLine":3,"endLine":4},"6":{"startLine":6,"endLine":7},"7":{"startLine":8,"endLine":9}}}}}},{"id":"brute-cost","kind":"case-probe","chapter":"The obvious way","eyebrow":"Count the work","title":"Each mismatch forks into skip-left and skip-right over the two suffixes. How fast does the call tree grow?","workspacePanel":"visualizer","summary":"At i = 1, j = 1 the values 4 and 2 differ, so the call forks into lines(2, 1) and lines(1, 2); picture that splitting repeat at every mismatch down the arrays.","options":[{"id":"exponential","label":"About 2^(m+n), doubling with each extra entry on either side","rationale":"Each mismatch advances one suffix or the other and branches in two, so a tree that can descend m + n levels reaches roughly 2^(m+n) calls.","isCorrect":true},{"id":"quadratic","label":"About (m+n) squared","rationale":"Squaring would count pairs of positions. The branching here forks in two at each mismatch, which compounds to 2^(m+n)."},{"id":"linear","label":"About m + n, one step per entry","rationale":"A single pass would suffice only if nothing branched; every mismatch forks into two recursive calls, so the work compounds far past m + n."}],"answer":"Around 2^(m+n). Each mismatch forks the search in two and advances one suffix, so a call tree up to m + n deep doubles its way to roughly 2^(m+n) calls.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"brute-cost-fork","state":{"arrays":[{"name":"nums1","values":[1,4,2],"i":1},{"name":"nums2","values":[1,2,4],"i":1}]}}]}},{"id":"repeated-work","kind":"case-probe","chapter":"The obvious way","eyebrow":"Name the waste","title":"What does the branching keep re-solving?","workspacePanel":"visualizer","summary":"Skipping from nums1 and skipping from nums2 both land on i = 2, j = 2, so the suffix pair starting there is solved twice.","options":[{"id":"prefix-pairs","label":"The best line count for the same pair of prefixes, over and over","rationale":"The most lines between two prefixes depends only on those prefixes, so computing it once per prefix pair removes the repeated search.","isCorrect":true},{"id":"read","label":"Reading the values","rationale":"Reading an entry is cheap; the cost is re-deciding the best line count for prefix pairs that recur."},{"id":"count","label":"Counting how many lines were drawn","rationale":"The count falls out for free; the explosion is in re-exploring the same prefix pairs along different branches."}],"answer":"The prefix-pair answers. The most non-crossing lines between two prefixes is fixed, so solving it once per pair of prefix lengths kills the repetition.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"repeated-work-overlap","state":{"arrays":[{"name":"nums1","values":[1,4,2],"i":2},{"name":"nums2","values":[1,2,4],"i":2}]}}]}},{"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-structure","state":{"grid":[[0,0,0],[0,0,0],[0,0,0]],"r":0,"c":0,"filled":[[0,0],[0,1],[0,2],[1,0],[2,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"table-bridge","kind":"info","chapter":"The idea","eyebrow":"Set up the table","title":"One cell per pair of prefixes","workspacePanel":"visualizer","body":["Since the answer for two prefixes is fixed, give every prefix pair its own slot: let dp[i][j] hold the most non-crossing lines between nums1's first i entries and nums2's first j entries.","Each cell is solved once. The job now is the rule that fills one cell from cells already computed, which comes down to the last entry of each prefix."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"table-bridge-state","state":{"grid":[[0,0,0],[0,0,0],[0,0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[0,2],[1,0],[2,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"match-or-not","kind":"case-probe","chapter":"The idea","eyebrow":"Find the cases","title":"Comparing the last entry of each prefix, what are the only two cases?","workspacePanel":"visualizer","summary":"dp[i][j] is being filled from the last entry of each prefix.","options":[{"id":"two","label":"The two last entries are equal, or they are not","rationale":"Whether the current values match is the single fork: equal values can be connected by a line, unequal ones cannot.","isCorrect":true},{"id":"three","label":"Equal, greater, or smaller","rationale":"The values are compared only for equality; their ordering by size is not part of the rule."},{"id":"len","label":"The prefixes are the same length or not","rationale":"Prefix length does not drive the rule; whether the two current values match does."}],"answer":"They match or they do not. That single test decides whether the two current entries can be joined by a line.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cases-state","state":{"arrays":[{"name":"nums1 prefix","values":[1],"i":0},{"name":"nums2 prefix","values":[1],"i":0}]}}]}},{"id":"match-diagonal","kind":"case-probe","chapter":"The idea","eyebrow":"Find the rule","title":"When the two values match, which earlier answer does the cell extend?","workspacePanel":"visualizer","summary":"The two current values are equal, so a line can join them.","options":[{"id":"diagonal","label":"The diagonal: both prefixes without these two entries, plus 1","rationale":"Drawing this line uses up the last entry of each prefix, leaving the smaller prefix pair on the diagonal, and the new line adds one to it.","isCorrect":true},{"id":"up","label":"The cell above, plus 1","rationale":"The cell above drops an entry from only one array; the new line consumes one entry from each, which is the diagonal."},{"id":"same","label":"The same cell, plus 1","rationale":"A cell cannot build on itself; the line builds on the strictly smaller diagonal prefix pair."}],"answer":"The diagonal plus 1. Equal values draw a line on top of the best count for both prefixes without them, dp[i-1][j-1] + 1.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"match-state","state":{"grid":[[0,0,0],[0,0,1],[0,0,0]],"r":1,"c":2,"filled":[[0,0],[0,1],[0,2],[1,0],[2,0],[1,2]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"no-match-max","kind":"case-probe","chapter":"The idea","eyebrow":"Find the rule","title":"When the values differ, the cell is the better of which two?","workspacePanel":"visualizer","summary":"A mismatch means at least one current entry goes unused.","options":[{"id":"up-left","label":"The cell above and the cell to the left","rationale":"Skipping the last entry of one array or the other gives the two candidate answers, and the better of them wins.","isCorrect":true},{"id":"diagonal","label":"The diagonal cell","rationale":"The diagonal drops an entry from both arrays at once, throwing away one that might still feed a line on its own side."},{"id":"sum","label":"The cell above plus the cell to the left","rationale":"Adding them would double-count lines they share. The mismatch case chooses the larger of the two skip results."}],"answer":"The larger of above and left. A mismatch skips the last entry of one array or the other, so dp takes max(dp[i-1][j], dp[i][j-1]).","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"nomatch-state","state":{"grid":[[0,0,0],[0,0,0],[0,0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[0,2],[1,0],[2,0],[1,1]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"An empty prefix draws no lines","workspacePanel":"visualizer","body":["The table has a row and a column for the empty prefix, all zeros: matching either array against nothing draws no lines.","Tracing nums1 = [1, 4, 2] against nums2 = [1, 2, 4], each interior cell either extends the diagonal on a match or takes the larger of its top and left neighbors."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"grid":[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],"r":0,"c":0,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Fill the table","title":"Fill the uncrossed-lines table","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cell-11","state":{"grid":[[0,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0],[1,1]],"labels":{"grid":"dp"},"changed":[]}},{"id":"cell-23","state":{"grid":[[0,0,0,0],[0,1,1,1],[0,1,1,2],[0,0,0,0]],"r":2,"c":3,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0],[1,1],[1,2],[1,3],[2,1],[2,2],[2,3]],"labels":{"grid":"dp"},"changed":[]}},{"id":"cell-32","state":{"grid":[[0,0,0,0],[0,1,1,1],[0,1,1,2],[0,1,2,0]],"r":3,"c":2,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0],[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2]],"labels":{"grid":"dp"},"changed":[]}},{"id":"cell-33","state":{"grid":[[0,0,0,0],[0,1,1,1],[0,1,1,2],[0,1,2,2]],"r":3,"c":3,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0],[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]],"labels":{"grid":"dp"},"changed":[]}}]},"beats":[{"id":"cell-11","title":"Cell (1,1): 1 vs 1. Match or mismatch, and what fills it?","summary":"The first interior cell.","prompt":"nums1's 1 and nums2's 1 are being compared.","options":[{"id":"one","label":"Match, so diagonal 0 + 1 = 1","rationale":"1 equals 1, so a line connects them and the cell extends the diagonal 0 by one.","isCorrect":true},{"id":"zero","label":"Mismatch, so max(above 0, left 0) = 0","rationale":"The values are equal, so the match rule applies and a line can be drawn here."},{"id":"edge","label":"It stays 0, no line yet","rationale":"Equal values mean a line right away, so the cell is 1, not 0."}],"answer":"Match. 1 equals 1, so diagonal 0 + 1 = 1."},{"id":"cell-23","title":"At cell (2,3), nums1's 4 meets nums2's 4. Which rule fills it?","summary":"The 4s sit at the current row and column.","prompt":"The neighbors are diagonal dp[1][2] = 1, above dp[1][3] = 1, left dp[2][2] = 1.","options":[{"id":"two","label":"Match, so diagonal 1 + 1 = 2","rationale":"Equal 4s draw a line on top of the diagonal answer of 1, giving 2: the 1-line and the 4-line do not cross.","isCorrect":true},{"id":"one","label":"Mismatch, so max(above 1, left 1) = 1","rationale":"4 equals 4, so this is a match; the cell extends the diagonal instead of taking a neighbor."},{"id":"three","label":"Diagonal 1 + 2 = 3","rationale":"A single new line adds exactly 1 to the diagonal, not 2."}],"answer":"Match. 4 equals 4, so diagonal 1 + 1 = 2."},{"id":"cell-32","title":"At cell (3,2), nums1's 2 meets nums2's 2. Which rule fills it?","summary":"A cell lower in the table.","prompt":"The neighbors are diagonal dp[2][1] = 1, above dp[2][2] = 1, left dp[3][1] = 1.","options":[{"id":"two","label":"Match, so diagonal 1 + 1 = 2","rationale":"Equal 2s extend the diagonal answer of 1 to 2: the 1-line then the 2-line, both ordered.","isCorrect":true},{"id":"left","label":"Take the left neighbor, dp[3][1] = 1","rationale":"A match does not read the neighbors; it extends the diagonal by one."},{"id":"three","label":"3, adding to the cell above","rationale":"The new line adds 1 to the diagonal, not to the cell above."}],"answer":"Match. 2 equals 2, so diagonal 1 + 1 = 2."},{"id":"cell-33","title":"At the corner (3,3), nums1's 2 meets nums2's 4. Which rule fills it?","summary":"The bottom-right cell holds the final count.","prompt":"The neighbors are diagonal dp[2][2] = 1, above dp[2][3] = 2, left dp[3][2] = 2.","options":[{"id":"two","label":"Mismatch, so max(2, 2) = 2","rationale":"2 and 4 differ, so the cell keeps the larger neighbor; both are 2, so the most non-crossing lines is 2.","isCorrect":true},{"id":"three","label":"Match, so diagonal + 1 = 2 + 1 = 3","rationale":"2 and 4 are not equal, so there is no line to draw here; you cannot fit all three lines without a crossing."},{"id":"four","label":"4, adding the two neighbors 2 + 2","rationale":"The mismatch rule keeps the larger neighbor, not their sum."}],"answer":"2. The corner is a mismatch, so max(2, 2) = 2, the most lines you can draw without crossing."}]},{"id":"reset-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","title":"Why not reset the cell to 0 when the values differ?","workspacePanel":"trace","summary":"Zeroing the cell on every mismatch feels tidy, and it is exactly right for a neighboring problem where the matched run must be contiguous. Borrow that rule here and watch what it does when a matching value sits on the far side of a gap.","pitfall":"The code below sets the cell to 0 on a mismatch instead of carrying the larger neighbor.","whyItMatters":"On nums1 = [5, 1, 5] and nums2 = [5, 9, 5], the reset wipes the table at the 1-vs-9 gap, so the second pair of 5s rebuilds from 0 and the count ends at 1. Two non-crossing lines exist: the two 5s. Carrying max(above, left) across the mismatch is what lets a later line keep the earlier progress instead of restarting.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def max_uncrossed_lines(nums1: list[int], nums2: list[int]) -> int:\n    m = len(nums1)\n    n = len(nums2)\n    dp = [[0] * (n + 1) for _ in range(m + 1)]\n    for i in range(1, m + 1):\n        for j in range(1, n + 1):\n            if nums1[i - 1] == nums2[j - 1]:\n                dp[i][j] = dp[i - 1][j - 1] + 1\n            else:\n                dp[i][j] = 0\n    return dp[m][n]","steps":[{"id":"match-5","title":"5 matches 5: the cell becomes 1","codeLine":8,"summary":"The diagonal extension works fine on a match.","state":{"grid":[[0,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0],[1,1]],"labels":{"grid":"dp"},"changed":[]}},{"id":"reset","title":"5 vs 9 differ: the cell is forced to 0","codeLine":10,"summary":"The earlier count of 1 is thrown away instead of carried forward.","state":{"grid":[[0,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,0]],"r":1,"c":2,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0],[1,1],[1,2]],"labels":{"grid":"dp"},"changed":[]}},{"id":"wrong","title":"The far 5s match, but only reach 1","codeLine":8,"summary":"Because the gap reset the diagonal, the corner reports 1 while the correct prefix DP would keep 2.","state":{"grid":[[0,0,0,0],[0,1,0,1],[0,0,0,0],[0,1,0,1]],"r":3,"c":3,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0],[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]],"labels":{"grid":"dp"},"changed":[]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const m = nums1.length;\nconst n = nums2.length;\nconst dp = Array.from({ length: (m + 1) }, () => Array((n + 1)).fill(0));\nfor (let i = 1; i < (m + 1); i++) {\n    for (let j = 1; j < (n + 1); j++) {\n        if (nums1[(i - 1)] === nums2[(j - 1)]) {\n            dp[i][j] = (dp[(i - 1)][(j - 1)] + 1);\n        } else {\n            dp[i][j] = 0;\n        }\n    }\n}\nreturn dp[m][n];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":13},"statementBundles":{"10":{"startLine":9,"endLine":12}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const m = nums1.length;\nconst n = nums2.length;\nconst dp = Array.from({ length: (m + 1) }, () => Array((n + 1)).fill(0));\nfor (let i = 1; i < (m + 1); i++) {\n    for (let j = 1; j < (n + 1); j++) {\n        if (nums1[(i - 1)] === nums2[(j - 1)]) {\n            dp[i][j] = (dp[(i - 1)][(j - 1)] + 1);\n        } else {\n            dp[i][j] = 0;\n        }\n    }\n}\nreturn dp[m][n];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":13},"statementBundles":{"10":{"startLine":9,"endLine":12}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int m = nums1.size();\nint n = nums2.size();\nList<List<Integer>> dp = new ArrayList<>();\nfor (int i = 0; i < (m + 1); i++) {\n    List<Integer> items0 = new ArrayList<>();\n    for (int index = 0; index < (n + 1); index++) {\n        items0.add(0);\n    }\n    dp.add(items0);\n}\nfor (int i = 1; i < (m + 1); i++) {\n    for (int j = 1; j < (n + 1); j++) {\n        if (nums1.get(i - 1) == nums2.get(j - 1)) {\n            dp.get(i).set(j, (dp.get(i - 1).get(j - 1) + 1));\n        } else {\n            dp.get(i).set(j, 0);\n        }\n    }\n}\nreturn dp.get(m).get(n);","lineMap":{"2":1,"3":2,"4":3,"5":11,"6":12,"7":13,"8":14,"9":15,"10":16,"11":20},"statementBundles":{"4":{"startLine":3,"endLine":10},"10":{"startLine":16,"endLine":19}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int m = nums1.Count;\nint n = nums2.Count;\nList<List<int>> dp = Enumerable.Range(0, m + 1).Select(_ => Enumerable.Repeat<int>(0, n + 1).ToList()).ToList();\nfor (int i = 1; i < m + 1; i++) {\n    for (int j = 1; j < n + 1; j++) {\n        if (nums1[i - 1] == nums2[j - 1]) {\n            dp[i][j] = dp[i - 1][j - 1] + 1;\n        } else {\n            dp[i][j] = 0;\n        }\n    }\n}\nreturn dp[m][n];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":13},"statementBundles":{"10":{"startLine":9,"endLine":12}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int m = nums1.size();\nint n = nums2.size();\nvector<vector<int>> dp = vector<vector<int>>((m + 1), vector<int>((n + 1), 0));\nfor (int i = 1; i < (m + 1); i++) {\n    for (int j = 1; j < (n + 1); j++) {\n        if (nums1[(i - 1)] == nums2[(j - 1)]) {\n            dp[i][j] = (dp[(i - 1)][(j - 1)] + 1);\n        } else {\n            dp[i][j] = 0;\n        }\n    }\n}\nreturn dp[m][n];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":13},"statementBundles":{"10":{"startLine":9,"endLine":12}}}}}},{"id":"edge-cases-bridge","kind":"info","chapter":"Edge cases","eyebrow":"Two inputs to stress","title":"Push the rule to its limits","workspacePanel":"visualizer","body":["The fill rule held on the worked example. Two inputs sit at opposite extremes and are worth checking before coding.","First, arrays that share no value at all. Second, arrays where every entry is the same value. The next two questions work through what the table does in each case."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-cases-bridge-state","state":{"grid":[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],"r":0,"c":0,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[2,0],[3,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"no-common-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"What is the answer when the arrays share no value?","workspacePanel":"visualizer","summary":"nums1 = [1, 2, 3], nums2 = [4, 5, 6].","options":[{"id":"zero","label":"0, no line can be drawn","rationale":"Every cell is a mismatch taking the max of neighbors that are all 0, so the table never rises above 0.","isCorrect":true},{"id":"one","label":"1, any single line","rationale":"No value of nums1 appears in nums2, so there is not even one pair to connect."},{"id":"three","label":"3, the shorter length","rationale":"Lines only come from equal values; with nothing in common the answer is 0."}],"answer":"0. With no shared value, every cell is a mismatch over zero neighbors, so the table stays 0.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"none-state","state":{"grid":[[0,0,0,0],[0,null,null,null],[0,null,null,null],[0,null,null,null]],"r":1,"c":1,"filled":[[0,1],[1,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"duplicates-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"What is the answer when every value is the same?","workspacePanel":"visualizer","summary":"nums1 = [1, 1, 1], nums2 = [1, 1].","options":[{"id":"two","label":"2, capped by the shorter array","rationale":"Each line uses one entry from each array in order, so the count cannot exceed the shorter array's length of 2.","isCorrect":true},{"id":"six","label":"6, every equal pair","rationale":"Lines must keep order and use each entry once; pairing every 1 with every 1 would cross, so the cap is the shorter length, 2."},{"id":"three","label":"3, the longer array","rationale":"nums2 only has two entries, so at most two ordered lines can land, not three."}],"answer":"2. Ordered lines use each entry once, so identical-value arrays give the shorter length, 2.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dup-state","state":{"grid":[[0,0,0],[0,1,null],[0,null,null],[0,null,null]],"r":1,"c":1,"filled":[[1,1]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","workspacePanel":"visualizer","summary":"One table, one comparison per cell, and the offset that bites.","ctaLabel":"Start coding","body":["Build a table with an extra zero row and column for the empty prefixes, then sweep the interior in order. dp[i][j] reads the entry one before i and one before j, so the array index trails the table index by one.","If the two current values match, the cell is the diagonal plus 1; otherwise it is the larger of the cell above and the cell to its left. Return the bottom-right cell."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"grid":[[0,0,0],[0,0,0],[0,0,0]],"r":0,"c":0,"filled":[[0,0],[0,1],[0,2],[1,0],[2,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the uncrossed-lines table","eyebrow":"Code the rule","summary":"Build the extra-boundary table, scan prefix pairs applying the match and mismatch rules, and return the bottom-right count.","workspacePanel":"code","checkpoints":[{"id":"init-dp-table","title":"Initialize the prefix DP table","description":"Read both array lengths and create a zero-filled table with one extra row and column.","commonMistakes":["Creating an m x n table instead of an (m+1) x (n+1) table","Using shared inner lists for the rows"],"hint":"Use the extra row and column for empty-prefix states.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_grid_dp_table","scope":"create-dp-table","readMode":"dp-value-query-v1","expected":{"firstAxisInputState":"nums1","secondAxisInputState":"nums2","firstAxisOffset":1,"secondAxisOffset":1}}]},"semanticSpec":{"intent":"Cache both input lengths and allocate a zero-filled (m+1) by (n+1) DP table.","doneWhen":"The implementation stores both lengths and creates an independent-row table where every cell starts at zero.","shouldFailWhen":"The table is the wrong size, rows alias each other, or one input length is not read.","roles":["first array length","second array length","dp table","empty-prefix boundary"],"mustProve":["Both input lengths are read before allocation.","The DP table has one extra row and column.","The table is initialized with zero values."],"mustNotAccept":["An m by n table with no empty-prefix boundary.","A table with aliased rows.","A scalar or one-dimensional state in place of the table."],"equivalentVariants":["Use a nested list comprehension with dimensions m + 1 and n + 1.","Use any equivalent independent-row matrix allocation."],"proofSnippets":[{"id":"py-uncrossed-lines-init-dp-table","language":"python","code":"class Solution:\n    def maxUncrossedLines(self, nums1: list[int], nums2: list[int]) -> int:\n        m = len(nums1)\n        n = len(nums2)\n        dp = [[0] * (n + 1) for _ in range(m + 1)]"}]}},{"id":"nested-loops","title":"Scan every pair of prefixes","description":"Use nested loops over i and j starting at 1 so each real prefix pair is filled once.","commonMistakes":["Starting at 0 and mixing real indices with empty-prefix states","Scanning only one array dimension"],"hint":"Rows represent prefixes of nums1; columns represent prefixes of nums2.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"loops_over_interior_grid","scope":"nested-loops","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Visit every non-empty prefix pair by looping i from 1..m and j from 1..n.","doneWhen":"The implementation has nested loops that cover all interior cells of the DP table.","shouldFailWhen":"Either loop starts from 0, a dimension is missing, or the loops skip valid prefix pairs.","roles":["row prefix index","column prefix index","interior DP cell"],"mustProve":["There is an outer loop over one array's prefixes.","There is an inner loop over the other array's prefixes.","Both loops begin after the empty-prefix boundary."],"mustNotAccept":["A single loop that cannot fill all prefix pairs.","Loops that overwrite the zero base row or column."],"equivalentVariants":["Use `for i in range(1, m + 1)` and `for j in range(1, n + 1)`.","Use equivalent while loops over the same bounds."],"proofSnippets":[{"id":"py-uncrossed-lines-nested-loops","language":"python","code":"class Solution:\n    def maxUncrossedLines(self, nums1: list[int], nums2: list[int]) -> int:\n        m = len(nums1)\n        n = len(nums2)\n        dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n        for i in range(1, m + 1):\n            for j in range(1, n + 1):\n                pass"}]}},{"id":"compare-values","title":"Compare the current values","description":"At each cell, compare nums1[i - 1] and nums2[j - 1] to decide whether a new line can be drawn.","commonMistakes":["Comparing nums1[i] and nums2[j] instead of offset indices","Comparing values from the same array"],"hint":"The DP row and column are one ahead of the actual array indices.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"branches_on_aligned_input_equality","scope":"character-comparison","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Branch on whether the current values from the two arrays are equal.","doneWhen":"The current DP cell uses an equality guard over nums1[i - 1] and nums2[j - 1].","shouldFailWhen":"The code skips the equality guard, uses wrong offsets, or compares an array to itself.","roles":["current nums1 value","current nums2 value","equality guard"],"mustProve":["The guard reads one value from each input array.","Both reads use the prefix-loop indices with a minus-one offset.","The guard separates match and non-match transitions."],"mustNotAccept":["Comparing `nums1[i]` with `nums2[j]`.","Using a one-branch recurrence that ignores value equality."],"equivalentVariants":["Use an equality condition on the aligned current values before updating the DP cell.","Store the two current values in temporaries and compare those temporaries."],"proofSnippets":[{"id":"py-uncrossed-lines-compare-values","language":"python","code":"class Solution:\n    def maxUncrossedLines(self, nums1: list[int], nums2: list[int]) -> int:\n        m = len(nums1)\n        n = len(nums2)\n        dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n        for i in range(1, m + 1):\n            for j in range(1, n + 1):\n                if nums1[i - 1] == nums2[j - 1]:\n                    pass\n                else:\n                    pass"}]}},{"id":"extend-match","title":"Extend a matching line","description":"When the current values match, add one to the diagonal subproblem.","commonMistakes":["Using top or left instead of the diagonal","Forgetting to add one for the new line"],"hint":"A matched pair consumes one value from each array, so it extends dp[i - 1][j - 1].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"extends_diagonal_predecessor","scope":"dp-update-match","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Write dp[i][j] as the diagonal predecessor plus one in the match branch.","doneWhen":"The match branch assigns dp[i][j] = dp[i - 1][j - 1] + 1 or an equivalent expression.","shouldFailWhen":"The update omits the diagonal, omits the plus one, or writes to the wrong cell.","roles":["diagonal predecessor","current DP cell","matched line"],"mustProve":["The update reads dp[i - 1][j - 1].","The update adds one for the current line.","The update targets the current DP cell."],"mustNotAccept":["Using only top or left in the match branch.","Copying the diagonal without adding one."],"equivalentVariants":["Use a temporary for the diagonal value, then assign that value plus one.","Use the direct diagonal-plus-one assignment."],"proofSnippets":[{"id":"py-uncrossed-lines-extend-match","language":"python","code":"class Solution:\n    def maxUncrossedLines(self, nums1: list[int], nums2: list[int]) -> int:\n        m = len(nums1)\n        n = len(nums2)\n        dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n        for i in range(1, m + 1):\n            for j in range(1, n + 1):\n                if nums1[i - 1] == nums2[j - 1]:\n                    dp[i][j] = dp[i - 1][j - 1] + 1\n                else:\n                    pass"}]}},{"id":"keep-best-mismatch","title":"Keep the best mismatch result","description":"When the current values differ, keep the better answer from skipping one value in either array.","commonMistakes":["Taking the minimum instead of the maximum","Reading the diagonal in the mismatch branch"],"hint":"If values differ, a non-crossing optimum either skips nums1[i - 1] or skips nums2[j - 1].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"takes_adjacent_predecessor_extremum","scope":"dp-update-no-match","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Use max(top, left) when the current values cannot be connected.","doneWhen":"The mismatch branch assigns dp[i][j] from the larger of dp[i - 1][j] and dp[i][j - 1].","shouldFailWhen":"The update chooses a smaller value, ignores one adjacent predecessor, or uses an unrelated cell.","roles":["top predecessor","left predecessor","current DP cell","best non-crossing count"],"mustProve":["The mismatch update reads both top and left predecessor cells.","The larger predecessor is stored in the current cell.","The update is used for the non-match branch."],"mustNotAccept":["Using min, addition, or diagonal-only logic for mismatches.","Skipping either top or left predecessor."],"equivalentVariants":["Use `max(dp[i - 1][j], dp[i][j - 1])`.","Use an equivalent conditional that keeps the larger adjacent value."],"proofSnippets":[{"id":"py-uncrossed-lines-keep-best-mismatch","language":"python","code":"class Solution:\n    def maxUncrossedLines(self, nums1: list[int], nums2: list[int]) -> int:\n        m = len(nums1)\n        n = len(nums2)\n        dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n        for i in range(1, m + 1):\n            for j in range(1, n + 1):\n                if nums1[i - 1] == nums2[j - 1]:\n                    dp[i][j] = dp[i - 1][j - 1] + 1\n                else:\n                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])"}]}},{"id":"return-result","title":"Return the completed table result","description":"Return dp[m][n], the best answer using both full arrays.","commonMistakes":["Returning dp[m - 1][n - 1]","Returning the whole table instead of the bottom-right value"],"hint":"The extra row and column mean the full arrays land at dp[m][n].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_bottom_right_cell","scope":"return-answer","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Return the bottom-right DP cell after all prefix pairs are processed.","doneWhen":"The function returns dp[m][n] after the nested loops complete.","shouldFailWhen":"The code returns a partial cell, a stale temporary, or the whole table.","roles":["bottom-right DP cell","full-array answer","returned value"],"mustProve":["The return reads the bottom-right table cell.","The returned cell corresponds to both full input arrays.","The return happens after the recurrence has filled the table."],"mustNotAccept":["Returning dp[m - 1][n - 1].","Returning a row, column, or table object."],"equivalentVariants":["Return `dp[m][n]` directly.","Store `dp[m][n]` in a temporary and return that temporary."],"proofSnippets":[{"id":"py-uncrossed-lines-return-result","language":"python","code":"class Solution:\n    def maxUncrossedLines(self, nums1: list[int], nums2: list[int]) -> int:\n        m = len(nums1)\n        n = len(nums2)\n        dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n        for i in range(1, m + 1):\n            for j in range(1, n + 1):\n                if nums1[i - 1] == nums2[j - 1]:\n                    dp[i][j] = dp[i - 1][j - 1] + 1\n                else:\n                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])\n\n        return dp[m][n]"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Each cell is the most non-crossing lines between two prefixes: extend the diagonal on a match, take the larger neighbor on a mismatch.","workspacePanel":"code","body":["No-crossing is just order-preserving matching in disguise: two lines cross exactly when their endpoints sit in opposite orders, so the answer is the longest ordered run of equal values, the same grid as longest common subsequence on numbers.","The match-versus-mismatch fork is the whole algorithm: equal values draw a line and consume one entry from each array, mismatches skip one entry from either side."],"takeaways":[{"title":"No crossing means matching in order","body":"Two lines cross only when their endpoints are ordered oppositely, so the most non-crossing lines is the longest order-preserving set of equal pairs."},{"title":"Match extends the diagonal, mismatch keeps the best","body":"Equal values give dp[i-1][j-1] + 1; unequal values take max(dp[i-1][j], dp[i][j-1]). Resetting to 0 instead would solve the contiguous version, not this one."},{"title":"One cell per prefix pair: O(m*n)","body":"Solving each of the m*n prefix pairs once costs O(m*n) time and space, replacing the brute force's roughly 2^(m+n) re-exploration of match sets."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
