{"id":"kth-smallest-element-in-a-sorted-matrix","title":"Kth Smallest Element in a Sorted Matrix","difficulty":"medium","patterns":["heap"],"primaryConcept":"heap-top-k","concepts":["heap-top-k"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"stacks-queues","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"matrix","primaryParam":"matrix","sizeMetric":"matrix-cells","constraints":["sorted"],"sizes":[9,16,25,36],"valueRange":{"min":-50,"max":50},"secondaryParams":{"k":{"strategy":"random-int"}}},"description":"Given an `n x n` matrix where each row and each column is sorted in non-decreasing order, return the `k`th smallest value in the matrix.\n\nFor this TraceCode exercise, use a min-heap frontier seeded with the first value from each row. Do not flatten and sort the whole matrix.","examples":[{"input":"matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8","output":"13","explanation":"The sorted order is [1,5,9,10,11,12,13,13,15], so the 8th value is 13."},{"input":"matrix = [[1,2],[1,3]], k = 2","output":"1","explanation":"Duplicates count separately. The sorted order is [1,1,2,3]."}],"constraints":[{"id":"1-n-300","text":"1 <= n <= 300","check":[{"kind":"sizeRange","target":"matrix","measure":"matrixRows","min":1,"max":300},{"kind":"valueRange","target":"matrix","selector":"arrayItemLengths","min":1,"max":300}]},{"id":"n-matrix-length-matrix-i-length","text":"n == len(matrix) == len(matrix[i])"},{"id":"10-9-matrix-i-j-10-9","text":"-10^9 <= matrix[i][j] <= 10^9","check":{"kind":"valueRange","target":"matrix","selector":"nestedArrayItems","min":-1000000000,"max":1000000000}},{"id":"each-row-and-each-column-is-sorted-in-non-decreasing-order","text":"Each row and each column is sorted in non-decreasing order."},{"id":"1-k-n-n","text":"1 <= k <= n * n"}],"starterCode":"class Solution:\n    def kthSmallest(self, matrix: list[list[int]], k: int) -> int:\n        # Your code here\n        pass","functionName":"kthSmallest","testCases":[{"id":"1","input":{"matrix":[[1,5,9],[10,11,13],[12,13,15]],"k":8},"expected":13,"description":"Classic 3x3 sample with duplicate 13 values."},{"id":"2","input":{"matrix":[[1,2],[1,3]],"k":2},"expected":1,"description":"Duplicate values count as separate entries."},{"id":"3","input":{"matrix":[[-5]],"k":1},"expected":-5,"description":"Single-cell matrix."},{"id":"4","input":{"matrix":[[1,3,5],[6,7,12],[11,14,14]],"k":6},"expected":11,"description":"Frontier must advance across several rows."},{"id":"5","input":{"matrix":[[1,2,3],[2,3,4],[3,4,5]],"k":5},"expected":3,"description":"Many duplicate middle values."},{"id":"hidden-1","input":{"matrix":[[1,4],[2,5]],"k":3},"expected":4,"description":"Column order matters when rows interleave."},{"id":"hidden-2","input":{"matrix":[[-10,-5,0],[-4,1,3],[2,4,9]],"k":4},"expected":0,"description":"Handles negative values and zero."},{"id":"hidden-3","input":{"matrix":[[1,3,7,10],[2,5,8,12],[4,6,9,13],[11,14,15,16]],"k":10},"expected":10,"description":"Larger frontier with interleaved rows."},{"id":"h4","input":{"matrix":[[1,2],[1,3]],"k":3},"description":"Duplicate values occupy separate rank positions.","expected":2},{"id":"h5","input":{"matrix":[[-5,-4],[-4,-3]],"k":2},"description":"Negative numbers preserve the same ordering rule.","expected":-4},{"id":"duplicate-rank-across-rows","input":{"matrix":[[1,2,2],[2,3,4],[5,6,7]],"k":4},"description":"Repeated values across rows each occupy their own kth rank.","expected":2},{"id":"negative-interleaved-two-by-two","input":{"matrix":[[-10,-5],[-6,-1]],"k":3},"description":"A small matrix can interleave negative row and column frontiers.","expected":-5}],"hints":[{"level":1,"content":"The first value in every row is a candidate for the next smallest value."},{"level":2,"content":"Use a min-heap to repeatedly remove the smallest frontier value.","revealPattern":true},{"level":3,"content":"When you pop a value from row `r` and column `c`, push `matrix[r][c + 1]` if that column exists."}],"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":"row-frontier-heap","name":"Row frontier min-heap","summary":"Seed the heap with the first value from each row, then pop and refill from the same row until the k-th value is on top.","decisionReason":"This is the intended approach because the heap state holds one next candidate per row and each pop advances only the row that supplied it.","complexity":{"time":"O(n + k log n)","space":"O(n)"},"tradeoffs":["Maintains heap entries as value, row, and column so each row frontier can move forward.","Uses the sorted rows without storing all n² values.","The heap size stays at most n, which keeps each pop and push small."],"isOptimal":true,"steps":["Push the first value from each row.","Pop the smallest frontier value.","Push the next value from that popped row.","After k - 1 pops, read the heap top."]},{"id":"column-frontier-heap","name":"Column frontier min-heap","summary":"Seed the heap with the first value from each column, then pop and refill from the same column.","decisionReason":"A column frontier returns the same kth smallest matrix value in O(n + k log n) time. The guided implementation advances rows because the trace and boundary checks already expose one candidate per row.","complexity":{"time":"O(n + k log n)","space":"O(n)"},"tradeoffs":["Maintains heap entries as value, row, and column with one active candidate per column.","Has the same big-O cost as the row version for a square matrix.","Choosing one direction keeps the implementation and dry run easier to follow."],"isViable":true,"isOptimal":false},{"id":"cell-frontier-with-visited","name":"Cell frontier with duplicate guard","summary":"Start from the top-left cell, pop the smallest active cell, and add its right and down neighbors if they have not been added.","decisionReason":"This still uses an ordered frontier, but it needs an extra visited-cell state to avoid adding the same matrix position twice.","complexity":{"time":"O(k log k)","space":"O(k)"},"tradeoffs":["Maintains a heap plus a visited set of matrix coordinates.","Can be useful when k is small, but the duplicate guard is easy to get wrong.","The row-frontier version avoids the visited set by advancing only within the popped row."],"isOptimal":false}]},"codingCheckpoints":[{"id":"init-heap","title":"Initialize the min-heap","description":"Create the heap that will hold row frontier entries.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"initializes_heap_storage","scope":"init-heap","readMode":"heap-value-query-v1"}]},"semanticSpec":{"intent":"Set up priority storage before any row frontier values are added.","doneWhen":"This step is done when the code creates an empty heap or priority queue for frontier entries.","shouldFailWhen":"This step should fail if no priority storage exists or if the solution starts by flattening and sorting the matrix.","roles":["heap storage","frontier entries"],"mustProve":["A heap-like storage value is initialized before frontier pushes.","The storage is later used by priority operations."],"mustNotAccept":["Using a plain result array with no priority behavior.","Sorting every matrix value instead of creating a heap frontier."],"equivalentVariants":["Use Python heapq with an empty list.","Use any language-native priority queue initialized before seeding."],"proofSnippets":[{"id":"py-kth-matrix-init-heap","language":"python","code":"def kthSmallest(matrix: list[list[int]], k: int) -> int:\n    heap = []"}]},"commonMistakes":["Flattening the matrix before trying to use the heap.","Storing only values without row and column coordinates."],"hint":"The heap needs enough information to know which row to advance after a pop."},{"id":"seed-heap","title":"Seed one value per row","description":"Push the first value from each row into the heap with its row and column coordinates.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"seeds_heap_from_input_values","scope":"row-front-seed","readMode":"heap-value-query-v1"}]},"semanticSpec":{"intent":"Build the initial sorted frontier from the first value of each row.","doneWhen":"This step is done when a scan over the matrix rows pushes row-frontier entries into the heap.","shouldFailWhen":"This step should fail if the heap starts empty during the pop loop or if it receives all matrix values.","roles":["matrix rows","first column","heap entry"],"mustProve":["The code scans the input rows.","Each pushed heap entry includes a matrix value and the row coordinate needed for later refill."],"mustNotAccept":["Pushing every cell before the selection loop.","Pushing only the first row and ignoring other row frontiers."],"equivalentVariants":["Loop over row indices and push `(matrix[row][0], row, 0)`.","Loop over rows with an index and push the first element plus coordinates."],"proofSnippets":[{"id":"py-kth-matrix-seed-heap","language":"python","code":"def kthSmallest(matrix: list[list[int]], k: int) -> int:\n    heap = []\n    for row in range(len(matrix)):\n        heappush(heap, (matrix[row][0], row, 0))"}]},"commonMistakes":["Seeding only matrix[0][0].","Forgetting to store row and column with the value."],"hint":"Every row contributes its first value as an active candidate."},{"id":"pop-smallest","title":"Pop smaller values first","description":"Remove the smallest heap entry k - 1 times so the next top becomes the answer.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"extracts_heap_values","scope":"rank-minus-one-pop","readMode":"heap-value-query-v1"}]},"semanticSpec":{"intent":"Use the priority queue to consume smaller frontier entries before reading the answer.","doneWhen":"This step is done when the solution repeatedly extracts from the heap before returning the final top value.","shouldFailWhen":"This step should fail if the code scans for the minimum manually or never removes heap entries.","roles":["heap top","popped value","row coordinate","column coordinate"],"mustProve":["The code performs a heap extraction.","The extracted entry exposes the row and column that produced the value."],"mustNotAccept":["Reading the heap top once without consuming earlier values.","Popping from an unrelated temporary array."],"equivalentVariants":["Use `heapq.heappop` in Python.","Use a native priority queue pop or poll operation."],"proofSnippets":[{"id":"py-kth-matrix-pop-smallest","language":"python","code":"def kthSmallest(matrix: list[list[int]], k: int) -> int:\n    heap = []\n    for row in range(len(matrix)):\n        heappush(heap, (matrix[row][0], row, 0))\n    for _ in range(k - 1):\n        value, row, col = heappop(heap)"}]},"commonMistakes":["Looping k times and then returning the next value.","Using a max-heap without reversing the priority."],"hint":"After k - 1 pops, the smallest remaining heap entry is the k-th matrix value."},{"id":"push-next","title":"Advance the popped row","description":"After popping an entry, push the next value from that same row if it exists.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"reinserts_projected_heap_values","scope":"guarded-row-successor","readMode":"heap-value-query-v1"}]},"semanticSpec":{"intent":"Refill the frontier from the same row that produced the popped value.","doneWhen":"This step is done when the pop loop checks the next column and pushes `(matrix[row][col + 1], row, col + 1)`.","shouldFailWhen":"This step should fail if the loop never refills the row, refills the wrong row, or pushes out-of-bounds values.","roles":["popped row","popped column","next column","refill entry"],"mustProve":["The code derives the next column from the popped column.","The pushed value comes from the same row as the popped heap entry."],"mustNotAccept":["Always pushing from row 0.","Pushing a next entry without checking the column bound."],"equivalentVariants":["Use `if col + 1 < len(matrix[0])` before the refill push.","Use any equivalent row-boundary guard tied to the popped column."],"proofSnippets":[{"id":"py-kth-matrix-push-next","language":"python","code":"def kthSmallest(matrix: list[list[int]], k: int) -> int:\n    heap = []\n    for row in range(len(matrix)):\n        heappush(heap, (matrix[row][0], row, 0))\n    for _ in range(k - 1):\n        value, row, col = heappop(heap)\n        if col + 1 < len(matrix[0]):\n            heappush(heap, (matrix[row][col + 1], row, col + 1))"}]},"commonMistakes":["Incrementing the row instead of the column.","Pushing a next value after the row is already exhausted."],"hint":"The popped coordinates tell you exactly which next value can enter the frontier."},{"id":"return-answer","title":"Return the heap top","description":"After k - 1 removals, return the value stored at the top of the heap.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"returns_heap_top","scope":"return-values","readMode":"heap-value-query-v1"}]},"semanticSpec":{"intent":"Read the k-th value from the heap after consuming the smaller frontier entries.","doneWhen":"This step is done when the function returns the value component of the heap top.","shouldFailWhen":"This step should fail if the function returns the last popped value too early or returns the whole heap entry.","roles":["heap top","answer value"],"mustProve":["The returned value is read from the heap after the pop/refill loop.","Only the matrix value component is returned, not the row and column metadata."],"mustNotAccept":["Returning the tuple or array heap entry.","Returning the value popped on the final iteration after running the loop k times."],"equivalentVariants":["Return `heap[0][0]` in Python.","Peek the priority queue and return its first field."],"proofSnippets":[{"id":"py-kth-matrix-return-answer","language":"python","code":"def kthSmallest(matrix: list[list[int]], k: int) -> int:\n    heap = []\n    for row in range(len(matrix)):\n        heappush(heap, (matrix[row][0], row, 0))\n    for _ in range(k - 1):\n        value, row, col = heappop(heap)\n        if col + 1 < len(matrix[0]):\n            heappush(heap, (matrix[row][col + 1], row, col + 1))\n    return heap[0][0]"}]},"commonMistakes":["Returning the full heap entry.","Popping k times and returning the next heap top."],"hint":"The loop removes exactly k - 1 smaller values, so the answer is now at the heap top."}],"slides":[{"id":"read-the-problem","kind":"info","chapter":"The problem","eyebrow":"Read the problem","title":"The kth smallest, by rank not by value","workspacePanel":"problem","body":["You are given an n by n matrix where every row reads left to right in non-decreasing order and every column reads top to bottom the same way. You return the kth smallest value, counting from the smallest up. Rank is by position, so a value that repeats fills more than one rank.","The matrix is sorted along each row and along each column, but not as a whole, so the kth smallest value cannot be read off any single position."]},{"id":"brute-force","kind":"code-trace","chapter":"The problem","eyebrow":"The obvious way","title":"Flatten every cell into one list, then sort it","summary":"Flattening and sorting reaches the answer, but watch how much ordering it does to values that sit far past the kth.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"flat = [value for row in matrix for value in row]\nflat.sort()\nreturn flat[k - 1]","steps":[{"id":"flatten","title":"Collect all nine cells into one flat list","codeLine":1,"summary":"Every value from all three rows lands in flat: [1, 5, 9, 10, 11, 13, 12, 13, 15], nine values regardless of k.","state":{"arrays":[{"name":"flat","values":[1,5,9,10,11,13,12,13,15]}]}},{"id":"sort-all","title":"Sort all nine values into order","codeLine":2,"summary":"The sort arranges the whole list into [1, 5, 9, 10, 11, 12, 13, 13, 15], ordering values ranked well below k = 8.","state":{"arrays":[{"name":"flat","values":[1,5,9,10,11,12,13,13,15]}]}},{"id":"index-k","title":"Read the value at position k - 1","codeLine":3,"summary":"With k = 8, position 7 holds 13, the 8th smallest, so the values ordered above it were sorted for nothing.","state":{"arrays":[{"name":"flat","values":[1,5,9,10,11,12,13,13,15],"current":7}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const flat = [];\nfor (const row of matrix) {\n    for (const value of row) {\n        flat.push(value);\n    }\n}\nflat.sort((a, b) => a - b);\nreturn flat[(k - 1)];","lineMap":{"1":1,"2":7,"3":8},"statementBundles":{"1":{"startLine":1,"endLine":6}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const flat: Array<number> = [];\nfor (const row of matrix) {\n    for (const value of row) {\n        flat.push(value);\n    }\n}\nflat.sort((a, b) => a - b);\nreturn flat[(k - 1)];","lineMap":{"1":1,"2":7,"3":8},"statementBundles":{"1":{"startLine":1,"endLine":6}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> flat = new ArrayList<>();\nfor (List<Integer> row : matrix) {\n    for (Integer value : row) {\n        flat.add(value);\n    }\n}\nCollections.sort(flat);\nreturn flat.get(k - 1);","lineMap":{"1":1,"2":7,"3":8},"statementBundles":{"1":{"startLine":1,"endLine":6}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> flat = new();\nforeach (var row in matrix) {\n    foreach (int value in row) {\n        flat.Add(value);\n    }\n}\nflat.Sort();\nreturn flat[k - 1];","lineMap":{"1":1,"2":7,"3":8},"statementBundles":{"1":{"startLine":1,"endLine":6}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> flat;\nfor (vector<int> row : matrix) {\n    for (int value : row) {\n        flat.push_back(value);\n    }\n}\nstable_sort(flat.begin(), flat.end());\nreturn flat[(k - 1)];","lineMap":{"1":1,"2":7,"3":8},"statementBundles":{"1":{"startLine":1,"endLine":6}}}}},"body":["It collects all n squared values, sorts every one of them, then reads the single slot k - 1."]},{"id":"sort-cost","kind":"case-probe","chapter":"The problem","eyebrow":"Name the waste","title":"For k = 8 of 9 cells, what work does the sort spend that the answer never uses?","workspacePanel":"visualizer","summary":"Flattening puts every cell into one list and sorts all nine values before reading slot k - 1.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"sorted-waste","state":{"nums":[1,5,9,10,11,12,13,13,15],"current":7,"used":[8],"labels":{"nums":"sorted flat"}}}]},"options":[{"id":"row-order","label":"It re-orders cells the rows already had in order","rationale":"Each row arrives sorted, so a full sort re-discovers an ordering that was handed to it. On an n by n matrix that is O(n^2 log n) work to rebuild structure the input already carried.","isCorrect":true},{"id":"none","label":"No waste, every cell must be compared to find the kth","rationale":"The rows are already sorted, so the input hands you a head start; comparing all n squared cells against each other from scratch throws that head start away."},{"id":"only-k","label":"It sorts exactly k cells, which is the minimum","rationale":"flat.sort() orders all n squared cells, not k; the answer reads one slot, but the sort paid to arrange every value including those ranked far past k."}],"answer":"It re-sorts order the rows already had. Every row is sorted on the way in, so flattening discards that and pays O(n^2 log n) to rebuild ordering the input already carried, including values ranked far past the kth."},{"id":"idea-bridge","kind":"info","chapter":"The idea","eyebrow":"Reframe the work","title":"Stop rebuilding order, start carrying less","workspacePanel":"visualizer","body":["Sorting spent its cost rebuilding the rows' existing order. The real question is how little of the matrix you need to keep live at once to pick off the smallest values one at a time.","Switch to the matrix view and look at it as a grid of untaken values. Before naming any structure, decide which cells could even be the next value you take."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"bridge-state","state":{"grid":[[1,5,9],[10,11,13],[12,13,15]],"labels":{"grid":"matrix"}}}]}},{"id":"enough-state","kind":"case-probe","chapter":"The idea","eyebrow":"Find the state","title":"To pick the next smallest value, which cells are even in the running?","workspacePanel":"visualizer","summary":"The matrix rows are each sorted, and you have taken nothing yet. You want to carry as few candidates as possible.","options":[{"id":"row-fronts","label":"Only the leftmost untaken value of each row","rationale":"Within a row, everything to the right of its leftmost untaken value is larger, so it cannot be the next smallest. That leaves exactly one live candidate per row, here 1, 10, and 12.","isCorrect":true},{"id":"all","label":"Every value not yet taken","rationale":"A value with a smaller untaken neighbor to its left in the same row can never be the next smallest, so holding all of them repeats the waste the sort did."},{"id":"first-col","label":"Only the first column","rationale":"The first column is the leftmost of each row only at the start; once a row's front is taken, its next candidate moves right, off the first column."}],"answer":"Only the leftmost untaken value of each row. Everything to its right in that row is larger, so each row offers exactly one live candidate: 1, 10, and 12.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"enough-state","state":{"grid":[[1,5,9],[10,11,13],[12,13,15]],"frontier":[[0,0],[1,0],[2,0]],"labels":{"grid":"matrix"}}}]}},{"id":"which-candidate","kind":"case-probe","chapter":"The idea","eyebrow":"Find the answer","title":"Holding one candidate per row, which one is the next smallest overall?","workspacePanel":"visualizer","summary":"The live candidates are 1 from row 0, 10 from row 1, and 12 from row 2.","options":[{"id":"min","label":"The smallest of the row candidates","rationale":"Every untaken value is at or behind one of these row fronts, so the global next smallest must be the smallest front. Of {1, 10, 12} that is 1.","isCorrect":true},{"id":"first","label":"Always the candidate from the top row","rationale":"The top row leads at the start, but a later row could hold a smaller front; the rule is smallest value, not topmost row."},{"id":"any","label":"Any of them, they are interchangeable","rationale":"Only the minimum front is guaranteed to have nothing smaller untaken; the others may have smaller values still waiting in other rows."}],"answer":"The smallest of the row candidates. Every untaken value sits at or behind a row front, so the minimum front, 1, is the next smallest overall.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"which-candidate","state":{"grid":[[1,5,9],[10,11,13],[12,13,15]],"frontier":[[1,0],[2,0]],"labels":{"grid":"matrix"},"filled":[[0,0]]}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which structure keeps the smallest row front cheap to find?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"heap":{"values":[1,10,12],"name":"heap","current":0}}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"Each pop advances exactly the row it came from","workspacePanel":"visualizer","body":["Seed a min-heap with the leftmost value of every row, tagging each with the row and column it came from. The heap root is the next smallest. Pop it, and slide that row's front one column right by pushing the next value from the same row.","The heap holds at most one candidate per row, so after popping k - 1 values its root is the kth smallest. Watch [[1, 5, 9], [10, 11, 13], [12, 13, 15]] settle on the 8th value, 13."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"heap":{"values":[1,10,12],"name":"heap","current":0},"grid":[[1,5,9],[10,11,13],[12,13,15]],"frontier":[[0,0],[1,0],[2,0]],"labels":{"grid":"matrix"}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Trace the heap","title":"Find the 8th smallest of [[1, 5, 9], [10, 11, 13], [12, 13, 15]]","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"seed-pop","state":{"heap":{"values":[1,10,12],"name":"heap"},"grid":[[1,5,9],[10,11,13],[12,13,15]],"frontier":[[0,0],[1,0],[2,0]],"labels":{"grid":"matrix"}}},{"id":"refill-row","state":{"heap":{"values":[10,12],"name":"heap"},"grid":[[1,5,9],[10,11,13],[12,13,15]],"frontier":[[1,0],[2,0]],"filled":[[0,0]],"labels":{"grid":"matrix"}}},{"id":"read-top","state":{"heap":{"values":[13],"name":"heap","current":0},"grid":[[1,5,9],[10,11,13],[12,13,15]],"frontier":[[2,1]],"filled":[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0]],"labels":{"grid":"matrix"}}}]},"beats":[{"id":"seed-pop","title":"The heap is seeded with 1, 10, 12. Which value pops first?","summary":"The frontier holds the leftmost value of each row: 1, 10, and 12.","options":[{"id":"one","label":"1, the heap root","rationale":"A min-heap surfaces its smallest, so 1 pops first. It is the global next smallest because everything else is at or behind a larger row front.","isCorrect":true},{"id":"ten","label":"10, from the middle row","rationale":"10 is a row front but not the smallest one; the heap pops the minimum, which is 1."},{"id":"any","label":"Whichever was pushed first","rationale":"A heap pops by value, not insertion order: the root is the smallest, 1, regardless of push order."}],"answer":"1. The min-heap root is the smallest front, and nothing untaken is smaller, so 1 is the next smallest."},{"id":"refill-row","title":"After popping 1 from row 0, which value enters the heap?","summary":"1 came from row 0, column 0. The other fronts, 10 and 12, are untouched.","options":[{"id":"five","label":"5, the next value in row 0","rationale":"The pop advances only the row it came from, so row 0's front slides one column right to matrix[0][1] = 5. The other rows keep their fronts.","isCorrect":true},{"id":"ten-down","label":"10, the value below in the same column","rationale":"Advancing down a column would re-enter values other rows already offer as their own fronts; the rule slides the popped row rightward, not downward."},{"id":"nothing","label":"Nothing, the heap just shrinks","rationale":"Row 0 still has more values, so its next one, 5, must enter; refilling keeps one live candidate per active row."}],"answer":"5. The popped value came from row 0, so that row's front moves right to matrix[0][1] = 5; rows 1 and 2 are unchanged."},{"id":"read-top","title":"After popping 7 values, what does returning the heap root give?","summary":"The pops so far, in order, were 1, 5, 9, 10, 11, 12, 13, which is k - 1 = 7 values.","options":[{"id":"thirteen","label":"13, the 8th smallest","rationale":"Seven pops removed the seven smallest values, so the root is now the 8th smallest. The duplicate 13 takes its own rank, so the answer is 13.","isCorrect":true},{"id":"fifteen","label":"15, the largest","rationale":"15 is the 9th smallest. After seven consumed values, the heap root is the 8th value."},{"id":"pop-again","label":"Nothing yet, pop once more first","rationale":"After exactly k - 1 pops the root is the kth value; popping an eighth time would consume the answer instead of reading it."}],"answer":"13. Seven pops cleared the seven smallest, so the root is the 8th smallest. The repeated 13 holds its own rank, so 13 is returned."}]},{"id":"pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","workspacePanel":"trace","title":"How many pops should run before reading the root?","summary":"The refill is in place, but the loop runs k times instead of k - 1. Watch the answer get popped out of the heap one step before it is read.","pitfall":"The loop below seeds and refills correctly, but it pops k times rather than k - 1, so the kth value is consumed before the root is returned.","whyItMatters":"Each pop removes the current smallest. After k pops, the root sits at the (k + 1)th value. On [[1, 2], [3, 4]] with k = 3 the sorted order is 1, 2, 3, 4, so the answer is 3; but popping three times removes 1, 2, then 3, leaving 4 at the root. Loop exactly k - 1 times so the kth value is still on top when you read it.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def kthSmallest(matrix: list[list[int]], k: int) -> int:\n    import heapq\n\n    heap: list[tuple[int, int, int]] = []\n    for row in range(len(matrix)):\n        heapq.heappush(heap, (matrix[row][0], row, 0))\n    for _ in range(k):\n        value, row, col = heapq.heappop(heap)\n        if col + 1 < len(matrix[0]):\n            heapq.heappush(heap, (matrix[row][col + 1], row, col + 1))\n    return heap[0][0]","steps":[{"id":"seed","title":"matrix = [[1, 2], [3, 4]], k = 3: seed each row front","codeLine":6,"summary":"The heap holds the two row fronts, 1 and 3. The sorted order is 1, 2, 3, 4, so the 3rd smallest is 3.","state":{"heap":{"values":[1,3],"name":"heap","current":0},"grid":[[1,2],[3,4]],"frontier":[[0,0],[1,0]],"labels":{"grid":"matrix"}}},{"id":"pop1","title":"Pop 1 (iteration 1), refill row 0 with 2","codeLine":8,"summary":"1 leaves and row 0 slides right to matrix[0][1] = 2, so the heap holds 2 and 3.","state":{"heap":{"values":[2,3],"name":"heap","current":0},"grid":[[1,2],[3,4]],"frontier":[[0,1],[1,0]],"filled":[[0,0]],"labels":{"grid":"matrix"}}},{"id":"pop2","title":"Pop 2 (iteration 2), row 0 has no next column","codeLine":8,"summary":"2 came from the last column of row 0, so no refill fires and only 3 remains. Two pops are done, but the loop runs once more.","state":{"heap":{"values":[3],"name":"heap","current":0},"grid":[[1,2],[3,4]],"frontier":[[1,0]],"filled":[[0,0],[0,1]],"labels":{"grid":"matrix"}}},{"id":"pop3","title":"Pop 3 (iteration 3) consumes the answer, refill row 1 with 4","codeLine":8,"summary":"The 3rd pop removes 3, the value that should have been returned, and row 1 refills with matrix[1][1] = 4. The heap now holds only 4.","state":{"heap":{"values":[4],"name":"heap","current":0},"grid":[[1,2],[3,4]],"frontier":[[1,1]],"filled":[[0,0],[0,1],[1,0]],"labels":{"grid":"matrix"}}},{"id":"wrong-return","title":"heap[0][0] returns 4 after three pops","codeLine":11,"summary":"Popping k = 3 times left the root at 4, so the function returns 4 when the correct 3rd smallest is 3. One fewer pop would have stopped with 3 on top.","state":{"heap":{"values":[4],"name":"heap","current":0},"grid":[[1,2],[3,4]],"frontier":[[1,1]],"filled":[[0,0],[0,1],[1,0]],"labels":{"grid":"matrix"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const heap = new Heap(compareHeapValues);\nfor (let row = 0; row < matrix.length; row++) {\n    heap.push([matrix[row][0], row, 0]);\n}\nfor (let i = 0; i < k; i++) {\n    const [value, row, col] = heap.pop();\n    if ((col + 1) < matrix[0].length) {\n        heap.push([matrix[row][(col + 1)], row, (col + 1)]);\n    }\n}\nreturn heap.root()[0];","lineMap":{"4":1,"5":2,"6":3,"7":5,"8":6,"9":7,"10":8,"11":11},"statementBundles":{"6":{"startLine":3,"endLine":4},"10":{"startLine":8,"endLine":10}},"alternateStyles":{"close-to-source":{"code":"const heap = new Heap(compareHeapValues);\nfor (let row = 0; row < matrix.length; row++) {\n    heap.push([matrix[row][0], row, 0]);\n}\nfor (let i = 0; i < k; i++) {\n    if (heap.isEmpty()) throw new Error(\"IndexError\");\n    const poppedValue = heap.pop();\n    const [value, row, col] = poppedValue;\n    if ((col + 1) < matrix[0].length) {\n        heap.push([matrix[row][(col + 1)], row, (col + 1)]);\n    }\n}\nreturn heap.root()[0];","lineMap":{"4":1,"5":2,"6":3,"7":5,"8":6,"9":9,"10":10,"11":13},"statementBundles":{"6":{"startLine":3,"endLine":4},"8":{"startLine":6,"endLine":8},"10":{"startLine":10,"endLine":12}}}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const heap: Heap<[number, number, number]> = new Heap<[number, number, number]>(compareHeapValues);\nfor (let row = 0; row < matrix.length; row++) {\n    heap.push([matrix[row][0], row, 0]);\n}\nfor (let i = 0; i < k; i++) {\n    const [value, row, col] = heap.pop()!;\n    if ((col + 1) < matrix[0].length) {\n        heap.push([matrix[row][(col + 1)], row, (col + 1)]);\n    }\n}\nreturn heap.root()![0];","lineMap":{"4":1,"5":2,"6":3,"7":5,"8":6,"9":7,"10":8,"11":11},"statementBundles":{"6":{"startLine":3,"endLine":4},"10":{"startLine":8,"endLine":10}},"alternateStyles":{"close-to-source":{"code":"const heap: Heap<[number, number, number]> = new Heap<[number, number, number]>(compareHeapValues);\nfor (let row = 0; row < matrix.length; row++) {\n    heap.push([matrix[row][0], row, 0]);\n}\nfor (let i = 0; i < k; i++) {\n    if (heap.isEmpty()) throw new Error(\"IndexError\");\n    const poppedValue = heap.pop()!;\n    const [value, row, col] = poppedValue;\n    if ((col + 1) < matrix[0].length) {\n        heap.push([matrix[row][(col + 1)], row, (col + 1)]);\n    }\n}\nreturn heap.root()![0];","lineMap":{"4":1,"5":2,"6":3,"7":5,"8":6,"9":9,"10":10,"11":13},"statementBundles":{"6":{"startLine":3,"endLine":4},"8":{"startLine":6,"endLine":8},"10":{"startLine":10,"endLine":12}}}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"PriorityQueue<List<Integer>> heap = new PriorityQueue<>((left, right) -> {\n    int commonLength = Math.min(left.size(), right.size());\n    for (int index = 0; index < commonLength; index++) {\n        int order = Integer.compare(left.get(index), right.get(index));\n        if (order != 0) return order;\n    }\n    return Integer.compare(left.size(), right.size());\n});\nfor (int row = 0; row < matrix.size(); row++) {\n    heap.offer(new ArrayList<>(List.of(matrix.get(row).get(0), row, 0)));\n}\nfor (int i = 0; i < k; i++) {\n    List<Integer> heapItem = heap.poll();\n    int value = heapItem.get(0);\n    int row = heapItem.get(1);\n    int col = heapItem.get(2);\n    if ((col + 1) < matrix.get(0).size()) {\n        heap.offer(new ArrayList<>(List.of(matrix.get(row).get(col + 1), row, (col + 1))));\n    }\n}\nreturn heap.peek().get(0);","lineMap":{"4":1,"5":9,"6":10,"7":12,"8":13,"9":17,"10":18,"11":21},"statementBundles":{"4":{"startLine":1,"endLine":8},"6":{"startLine":10,"endLine":11},"8":{"startLine":13,"endLine":16},"10":{"startLine":18,"endLine":20}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"PriorityQueue<(int, int, int), (int, int, int)> heap = new();\nfor (int row = 0; row < matrix.Count; row++) {\n    (int, int, int) heapEntry = (matrix[row][0], row, 0);\n    heap.Enqueue(heapEntry, heapEntry);\n}\nfor (int i = 0; i < k; i++) {\n    var (value, row, col) = heap.Dequeue();\n    if (col + 1 < matrix[0].Count) {\n        (int, int, int) heapEntry = (matrix[row][col + 1], row, col + 1);\n        heap.Enqueue(heapEntry, heapEntry);\n    }\n}\nreturn heap.Peek().Item1;","lineMap":{"4":1,"5":2,"6":3,"7":6,"8":7,"9":8,"10":9,"11":13},"statementBundles":{"6":{"startLine":3,"endLine":5},"10":{"startLine":9,"endLine":12}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<tuple<int, int, int>> heap;\nfor (int row = 0; row < matrix.size(); row++) {\n    heap.push_back(tuple<int, int, int>{matrix[row][0], row, 0}); push_heap(heap.begin(), heap.end(), greater<>());\n}\nfor (int i = 0; i < k; i++) {\n    auto [value, row, col] = heapPopValue(heap);\n    if ((col + 1) < matrix[0].size()) {\n        heap.push_back(tuple<int, int, int>{matrix[row][(col + 1)], row, (col + 1)}); push_heap(heap.begin(), heap.end(), greater<>());\n    }\n}\nreturn get<0>(heap[0]);","lineMap":{"4":1,"5":2,"6":3,"7":5,"8":6,"9":7,"10":8,"11":11},"statementBundles":{"6":{"startLine":3,"endLine":4},"10":{"startLine":8,"endLine":10}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["The seed, the pop, and the rightward refill carried the 3 by 3 matrix cleanly. The inputs that stress them are the ones where a row runs out or where the heap holds only one candidate.","Two are worth tracing: a row whose front reaches its last column, and a 1 by 1 matrix."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"heap":{"values":[10,12],"name":"heap","current":0},"grid":[[1,5,9],[10,11,13],[12,13,15]],"frontier":[[1,0],[2,0]],"filled":[[0,0],[0,1],[0,2]],"labels":{"grid":"matrix"}}}]}},{"id":"edge-row-exhausted","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"When the popped value was a row's last column, what should refill that row?","workspacePanel":"visualizer","summary":"In row 0 of matrix = [[1, 5, 9], ...], 9 sat in the last column and has just been popped.","options":[{"id":"nothing","label":"Nothing, that row has no more values","rationale":"Column 2 is the last in a 3-wide row, so col + 1 is out of bounds. The guard col + 1 < cols skips the push, and row 0 simply drops out of the frontier.","isCorrect":true},{"id":"wrap","label":"The first value of the row again","rationale":"Wrapping back would re-offer a value already taken; an exhausted row contributes nothing further and is left out."},{"id":"next-row","label":"The first value of the next row","rationale":"Each row owns its own front; row 0 running out does not pull row 1's values forward, and rows 1 and 2 already hold their own heap entries."}],"answer":"Nothing. col + 1 falls off the last column, so the guard skips the push and row 0 leaves the frontier while the other rows keep their candidates.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"row-exhausted","state":{"heap":{"values":[10,12],"name":"heap"},"grid":[[1,5,9],[10,11,13],[12,13,15]],"r":0,"c":2,"frontier":[[1,0],[2,0]],"filled":[[0,0],[0,1]],"labels":{"grid":"matrix"}}}]}},{"id":"edge-single-cell","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"On a 1 by 1 matrix with k = 1, how many pops run?","workspacePanel":"visualizer","summary":"matrix = [[-5]], k = 1. The heap is seeded with the single value -5.","options":[{"id":"zero","label":"None, the root is already the answer","rationale":"k - 1 is 0, so the pop loop never runs. The seeded root, -5, is the 1st smallest and is returned directly.","isCorrect":true},{"id":"one","label":"One pop, then read what is left","rationale":"Popping once would empty the only entry and leave nothing to read; with k = 1 the answer is the seed itself, so zero pops run."},{"id":"crash","label":"It cannot run, the refill has no next column","rationale":"The refill is guarded by col + 1 < cols and never fires here, but nothing forces it: with zero pops the loop body never executes at all."}],"answer":"None. k - 1 = 0 pops, so the loop is skipped and the seeded root -5 is returned as the 1st smallest.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-cell","state":{"heap":{"values":[-5],"name":"heap","current":0},"grid":[[-5]],"frontier":[[0,0]],"labels":{"grid":"matrix"}}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","workspacePanel":"visualizer","ctaLabel":"Start coding","summary":"Seed one front per row, pop the smallest k - 1 times advancing only the popped row, then read the root.","body":["Start an empty min-heap and seed it with the first value of every row, tagged with its row and column. Then pop the smallest k - 1 times; after each pop, slide that same row's front one column right, but only while a next column exists.","Once k - 1 values are gone, the kth smallest sits at the heap root, and that value is what you return."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"heap":{"values":[1,10,12],"name":"heap","current":0},"grid":[[1,5,9],[10,11,13],[12,13,15]],"frontier":[[0,0],[1,0],[2,0]],"labels":{"grid":"matrix"}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the row-frontier heap","eyebrow":"Build the solution","summary":"Seed row fronts, pop and refill k - 1 times, then return the heap root value.","workspacePanel":"code","checkpoints":[{"id":"init-heap","title":"Initialize the min-heap","description":"Create the heap that will hold row frontier entries.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"initializes_heap_storage","scope":"init-heap","readMode":"heap-value-query-v1"}]},"semanticSpec":{"intent":"Set up priority storage before any row frontier values are added.","doneWhen":"This step is done when the code creates an empty heap or priority queue for frontier entries.","shouldFailWhen":"This step should fail if no priority storage exists or if the solution starts by flattening and sorting the matrix.","roles":["heap storage","frontier entries"],"mustProve":["A heap-like storage value is initialized before frontier pushes.","The storage is later used by priority operations."],"mustNotAccept":["Using a plain result array with no priority behavior.","Sorting every matrix value instead of creating a heap frontier."],"equivalentVariants":["Use Python heapq with an empty list.","Use any language-native priority queue initialized before seeding."],"proofSnippets":[{"id":"py-kth-matrix-init-heap","language":"python","code":"def kthSmallest(matrix: list[list[int]], k: int) -> int:\n    heap = []"}]},"commonMistakes":["Flattening the matrix before trying to use the heap.","Storing only values without row and column coordinates."],"hint":"The heap needs enough information to know which row to advance after a pop."},{"id":"seed-heap","title":"Seed one value per row","description":"Push the first value from each row into the heap with its row and column coordinates.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"seeds_heap_from_input_values","scope":"row-front-seed","readMode":"heap-value-query-v1"}]},"semanticSpec":{"intent":"Build the initial sorted frontier from the first value of each row.","doneWhen":"This step is done when a scan over the matrix rows pushes row-frontier entries into the heap.","shouldFailWhen":"This step should fail if the heap starts empty during the pop loop or if it receives all matrix values.","roles":["matrix rows","first column","heap entry"],"mustProve":["The code scans the input rows.","Each pushed heap entry includes a matrix value and the row coordinate needed for later refill."],"mustNotAccept":["Pushing every cell before the selection loop.","Pushing only the first row and ignoring other row frontiers."],"equivalentVariants":["Loop over row indices and push `(matrix[row][0], row, 0)`.","Loop over rows with an index and push the first element plus coordinates."],"proofSnippets":[{"id":"py-kth-matrix-seed-heap","language":"python","code":"def kthSmallest(matrix: list[list[int]], k: int) -> int:\n    heap = []\n    for row in range(len(matrix)):\n        heappush(heap, (matrix[row][0], row, 0))"}]},"commonMistakes":["Seeding only matrix[0][0].","Forgetting to store row and column with the value."],"hint":"Every row contributes its first value as an active candidate."},{"id":"pop-smallest","title":"Pop smaller values first","description":"Remove the smallest heap entry k - 1 times so the next top becomes the answer.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"extracts_heap_values","scope":"rank-minus-one-pop","readMode":"heap-value-query-v1"}]},"semanticSpec":{"intent":"Use the priority queue to consume smaller frontier entries before reading the answer.","doneWhen":"This step is done when the solution repeatedly extracts from the heap before returning the final top value.","shouldFailWhen":"This step should fail if the code scans for the minimum manually or never removes heap entries.","roles":["heap top","popped value","row coordinate","column coordinate"],"mustProve":["The code performs a heap extraction.","The extracted entry exposes the row and column that produced the value."],"mustNotAccept":["Reading the heap top once without consuming earlier values.","Popping from an unrelated temporary array."],"equivalentVariants":["Use `heapq.heappop` in Python.","Use a native priority queue pop or poll operation."],"proofSnippets":[{"id":"py-kth-matrix-pop-smallest","language":"python","code":"def kthSmallest(matrix: list[list[int]], k: int) -> int:\n    heap = []\n    for row in range(len(matrix)):\n        heappush(heap, (matrix[row][0], row, 0))\n    for _ in range(k - 1):\n        value, row, col = heappop(heap)"}]},"commonMistakes":["Looping k times and then returning the next value.","Using a max-heap without reversing the priority."],"hint":"After k - 1 pops, the smallest remaining heap entry is the k-th matrix value."},{"id":"push-next","title":"Advance the popped row","description":"After popping an entry, push the next value from that same row if it exists.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"reinserts_projected_heap_values","scope":"guarded-row-successor","readMode":"heap-value-query-v1"}]},"semanticSpec":{"intent":"Refill the frontier from the same row that produced the popped value.","doneWhen":"This step is done when the pop loop checks the next column and pushes `(matrix[row][col + 1], row, col + 1)`.","shouldFailWhen":"This step should fail if the loop never refills the row, refills the wrong row, or pushes out-of-bounds values.","roles":["popped row","popped column","next column","refill entry"],"mustProve":["The code derives the next column from the popped column.","The pushed value comes from the same row as the popped heap entry."],"mustNotAccept":["Always pushing from row 0.","Pushing a next entry without checking the column bound."],"equivalentVariants":["Use `if col + 1 < len(matrix[0])` before the refill push.","Use any equivalent row-boundary guard tied to the popped column."],"proofSnippets":[{"id":"py-kth-matrix-push-next","language":"python","code":"def kthSmallest(matrix: list[list[int]], k: int) -> int:\n    heap = []\n    for row in range(len(matrix)):\n        heappush(heap, (matrix[row][0], row, 0))\n    for _ in range(k - 1):\n        value, row, col = heappop(heap)\n        if col + 1 < len(matrix[0]):\n            heappush(heap, (matrix[row][col + 1], row, col + 1))"}]},"commonMistakes":["Incrementing the row instead of the column.","Pushing a next value after the row is already exhausted."],"hint":"The popped coordinates tell you exactly which next value can enter the frontier."},{"id":"return-answer","title":"Return the heap top","description":"After k - 1 removals, return the value stored at the top of the heap.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"returns_heap_top","scope":"return-values","readMode":"heap-value-query-v1"}]},"semanticSpec":{"intent":"Read the k-th value from the heap after consuming the smaller frontier entries.","doneWhen":"This step is done when the function returns the value component of the heap top.","shouldFailWhen":"This step should fail if the function returns the last popped value too early or returns the whole heap entry.","roles":["heap top","answer value"],"mustProve":["The returned value is read from the heap after the pop/refill loop.","Only the matrix value component is returned, not the row and column metadata."],"mustNotAccept":["Returning the tuple or array heap entry.","Returning the value popped on the final iteration after running the loop k times."],"equivalentVariants":["Return `heap[0][0]` in Python.","Peek the priority queue and return its first field."],"proofSnippets":[{"id":"py-kth-matrix-return-answer","language":"python","code":"def kthSmallest(matrix: list[list[int]], k: int) -> int:\n    heap = []\n    for row in range(len(matrix)):\n        heappush(heap, (matrix[row][0], row, 0))\n    for _ in range(k - 1):\n        value, row, col = heappop(heap)\n        if col + 1 < len(matrix[0]):\n            heappush(heap, (matrix[row][col + 1], row, col + 1))\n    return heap[0][0]"}]},"commonMistakes":["Returning the full heap entry.","Popping k times and returning the next heap top."],"hint":"The loop removes exactly k - 1 smaller values, so the answer is now at the heap top."}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Keep one front per sorted row in a min-heap; pop k - 1 times, advancing only the popped row, and the root is the kth smallest.","workspacePanel":"code","body":["The shift from flattening and sorting to a row-front heap is refusing to re-order what the rows already had in order: only the leftmost untaken value of each row can be the next smallest, so the heap never carries more than n candidates.","Seeding is O(n), and each of the k - 1 pops does O(log n) work on a heap of size at most n, so the cost is O(n + k log n) time and O(n) space, down from O(n^2 log n) to sort every cell."],"takeaways":[{"title":"One live candidate per row","body":"Everything right of a row's front is larger, so only the n row fronts compete for next smallest, and an n-sized heap holds them all."},{"title":"A pop advances its own row","body":"The popped value's row and column tell you exactly which value enters next: slide that row right by one column, guarded so an exhausted row is dropped."},{"title":"Stop at k - 1 pops","body":"Removing the k - 1 smaller values leaves the kth at the root; one extra pop would consume the answer and return the (k + 1)th."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
