Linked List Operations and Sorted Matrix Search
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement a driver function solve_linked_list_and_matrix(values, matrix, target) that combines two singly linked list tasks with a 2D sorted grid search:
def solve_linked_list_and_matrix(
values: List[int], matrix: List[List[int]], target: int
) -> Dict[str, object]:
Your implementation should build an actual singly linked list of nodes from values and perform three operations:
- Minimum Node Value (
find_min): Traverse the non-empty linked list and compute its smallest integer. - In-Place Pointer Reversal (
reverse_list): Reverse the linked list in place by rewiring existing node links (without allocating new list nodes) and collect the resulting node sequence back into a Python list of integers. - 2D Monotone Grid Lookup (
search_matrix): Given anm x ninteger gridmatrixin which each row increases or stays flat from left to right and each column increases or stays flat from top to bottom, determine whethertargetappears in any cell.
Return a dictionary containing all three answers under exact keys:
{
"minimum": <smallest integer in the linked list>,
"reversed": <list of integers from the reversed linked list>,
"found": <True if target is present in matrix, else False>,
}
Examples
Example 1
Input:
values = [5, -2, 9, 4]
matrix = [
[2, 6, 10],
[4, 8, 12],
[7, 11, 15]
]
target = 8
Output:
{"minimum": -2, "reversed": [4, 9, -2, 5], "found": True}
Walk-through: Building the chain 5 -> -2 -> 9 -> 4 yields -2 as the smallest node value, and flipping the node links produces 4 -> 9 -> -2 -> 5. In matrix, 8 sits at row 1, column 1, so "found" is True.
Example 2
Input:
values = [7, 3]
matrix = [
[1, 5],
[3, 9]
]
target = 6
Output:
{"minimum": 3, "reversed": [3, 7], "found": False}
Walk-through: Across 7 -> 3, the smaller element is 3 and the reversed order is [3, 7]. Neither row [1, 5] nor row [3, 9] contains 6, so "found" is False.
Constraints
1 <= len(values) <= 10^4-10^6 <= values[i] <= 10^61 <= m, n <= 500, wherem = len(matrix)andn = len(matrix[0])- Every row of
matrixis sorted in non-decreasing order (matrix[r][c] <= matrix[r][c + 1]). - Every column of
matrixis sorted in non-decreasing order (matrix[r][c] <= matrix[r + 1][c]).
Step-by-step walkthrough
Understand the three sub-problems
One entry-point function,
solve_linked_list_and_matrix(values, matrix, target), bundles three classic pointer and grid tasks and returns{"minimum": int, "reversed": List[int], "found": bool}:- Part 1 (
find_min): Given the head of a non-empty singly linked list (1 <= N <= 10^4), return its smallest integer. - Part 2 (
reverse_list): Reverse that linked list in place (rewiring existing nodes without creating new ones) and return the new head. - Part 3 (
search_matrix): Determine whethertargetappears in anm x nmatrix (1 <= m, n <= 500) where every row is sorted left-to-right and every column is sorted top-to-bottom.
Notice two practical details about the setup:
- The automated judge passes
valuesas a plain Python list (like[5, -2, 9, 4]), so we build a genuineListNodechain fromvalues, runfind_minandreverse_liston those nodes, and convert the reversed chain back into a list for the judge. - Because
reverse_listmutates the.nextlinks of the existing nodes in place, we must computefind_min(head)before callingreverse_list(head).
- Part 1 (
Build the linked list and find its minimum (Part 1)
A singly linked list is a chain of
ListNodeobjects where each node holds one value (val) and one reference (next) pointing to the following node, ending atNone:head -> [5 | *-]---> [-2 | *-]---> [9 | *-]---> [4 | None]To build this chain cleanly in O(N) time without tracking a tail pointer, walk
valuesin reverse and prepend each new node onto the front ofhead.To find the minimum, initialize
smallest = head.val(never initialize to0, which would give the wrong answer when every node is positive!) and advance anodecursor through the rest of the chain:class ListNode: """One node of a singly linked list, e.g. ListNode(5, ListNode(-2, None)).""" def __init__(self, val: int, next_node: Optional["ListNode"] = None): self.val = val self.next = next_node def build_list(values: List[int]) -> Optional[ListNode]: """Convert `[5, -2, 9, 4]` into `5 -> -2 -> 9 -> 4 -> None` by prepending from back to front.""" # head: Optional[ListNode] — front of the chain built so far (None when empty) head: Optional[ListNode] = None for val in reversed(values): head = ListNode(val, head) return head def find_min(head: ListNode) -> int: """Part 1: scan a non-empty linked list once and return its minimum integer.""" if head is None: raise ValueError("Linked list must be non-empty") # Initialize from head.val (not 0!) so lists of all-positive integers work properly smallest = head.val node = head.next while node is not None: if node.val < smallest: smallest = node.val node = node.next return smallestReverse the linked list in place with three pointers (Part 2)
To reverse the chain in place, we want every arrow
A -> Bto flip intoA <- B, with the original head now pointing toNone.Here is the trap: as soon as we overwrite
current.next = prev, we cut the link fromcurrentto the rest of the unreversed chain! To avoid detaching the remaining suffix, we savenext_node = current.nextbefore changingcurrent.next:Before flipping `current = -2`: prev current next_node | | | [5 | None] [-2 | *-]-----> [9 | *-]---> [4 | None] Step A: next_node = current.next (hold onto node 9!) Step B: current.next = prev (flip -2's arrow back to 5) Step C: prev = current (advance prev to -2) Step D: current = next_node (advance current to 9) After flipping `-2`: prev current | | None <--- [5] <-[-2] [9 | *-]---> [4 | None]Why use a
whileloop instead of recursion? WithNup to10,000, a recursive function pushes10,000stack frames and crashes against Python's default recursion limit of1,000. The three-pointer loop uses O(1) extra memory for any list length.def to_values(head: Optional[ListNode]) -> List[int]: """Walk a linked list from `head` to `None` and collect its integers into a Python list.""" result: List[int] = [] node = head while node is not None: result.append(node.val) node = node.next return result def reverse_list(head: Optional[ListNode]) -> Optional[ListNode]: """Part 2: reverse a singly linked list in place and return the new head.""" # prev: head of the already-reversed prefix (starts at None, which becomes the new tail's .next) # current: next unreversed node whose .next pointer we are about to flip prev: Optional[ListNode] = None current: Optional[ListNode] = head while current is not None: # Save `current.next` BEFORE overwriting it, otherwise the rest of the chain is lost next_node = current.next current.next = prev prev = current current = next_node # When `current` hits None, `prev` sits on the original tail — our new head return prevMatrix search: why top-left gets stuck, and top-right works (Part 3)
How can we search an
m x ngrid where rows grow left-to-right and columns grow top-to-bottom?- Scanning every cell takes O(m * n) time and ignores both sorted directions.
- Binary searching each of the
mrows takes O(m log n) time, ignoring column sorting. - What if we start at the top-left cell
(0, 0)? Both moving right and moving down make numbers larger — so ifmatrix[0][0] < target, we cannot tell whether to go right or down!
Now look at the top-right corner
(0, n - 1)instead:smaller <--- [top-right] | v largerAt
(row, col)= top-right of the remaining candidate grid, the two directions point opposite ways:- Everything to the left in
rowis<= current_val. - Everything below in
colis>= current_val.
So a single comparison with
targetalways eliminates an entire row or an entire column:current_val == target: we found it — returnTrue.current_val > target: every cell below(row, col)incolis even larger (>= current_val > target), sotargetcannot be anywhere in columncol. Cross out that column (col -= 1).current_val < target: every cell left of(row, col)inrowis even smaller (<= current_val < target), sotargetcannot be anywhere in rowrow. Cross out that row (row += 1).
Code the staircase matrix search
After crossing out a column or a row,
(row, col)is once again the top-right corner of the remaining sub-rectangle! Since each iteration incrementsrow(at mostmtimes) or decrementscol(at mostntimes), the loop runs at mostm + nsteps:def search_matrix(matrix: List[List[int]], target: int) -> bool: """Part 3: search an m x n row-sorted and column-sorted matrix from the top-right corner.""" if not matrix or not matrix[0]: return False num_rows = len(matrix) num_cols = len(matrix[0]) # Start at top-right: moving left decreases values, moving down increases values row = 0 col = num_cols - 1 while row < num_rows and col >= 0: current_val = matrix[row][col] if current_val == target: return True if current_val > target: # Every cell below `(row, col)` in this column is >= current_val > target; rule out column col -= 1 else: # Every cell left of `(row, col)` in this row is <= current_val < target; rule out row row += 1 return FalseTrace through Example 1
Let's trace
values = [5, -2, 9, 4],matrix = [[2, 6, 10], [4, 8, 12], [7, 11, 15]], andtarget = 8:- Build & find minimum:
headis5 -> -2 -> 9 -> 4 -> None. Scanning updatessmallestfrom5to-2, returning-2. - Reverse:
prevadvances through5 -> None,-2 -> 5 -> None,9 -> -2 -> 5 -> None, and4 -> 9 -> -2 -> 5 -> None, giving[4, 9, -2, 5]. - Staircase walk for
target = 8:
Grid: Step 1: (0, 2) -> 10 > 8, drop col 2 -> move left to (0, 1) [ 2 6 <-10 ] Step 2: (0, 1) -> 6 < 8, drop row 0 -> move down to (1, 1) | Step 3: (1, 1) -> 8 == 8 -> return True! v [ 4 (8) 12 ] [ 7 11 15 ]- Build & find minimum:
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class ListNode: """One node of a singly linked list, e.g. ListNode(5, ListNode(-2, None)).""" def __init__(self, val: int, next_node: Optional["ListNode"] = None): self.val = val self.next = next_node def build_list(values: List[int]) -> Optional[ListNode]: """Convert `[5, -2, 9, 4]` into `5 -> -2 -> 9 -> 4 -> None` by prepending from back to front.""" # head: Optional[ListNode] — front of the chain built so far (None when empty) head: Optional[ListNode] = None for val in reversed(values): head = ListNode(val, head) return head def to_values(head: Optional[ListNode]) -> List[int]: """Walk a linked list from `head` to `None` and collect its integers into a Python list.""" result: List[int] = [] node = head while node is not None: result.append(node.val) node = node.next return result def find_min(head: ListNode) -> int: """Part 1: scan a non-empty linked list once and return its minimum integer.""" if head is None: raise ValueError("Linked list must be non-empty") # Initialize from head.val (not 0!) so lists of all-positive integers work properly smallest = head.val node = head.next while node is not None: if node.val < smallest: smallest = node.val node = node.next return smallest def reverse_list(head: Optional[ListNode]) -> Optional[ListNode]: """Part 2: reverse a singly linked list in place and return the new head.""" # prev: head of the already-reversed prefix (starts at None, which becomes the new tail's .next) # current: next unreversed node whose .next pointer we are about to flip prev: Optional[ListNode] = None current: Optional[ListNode] = head while current is not None: # Save `current.next` BEFORE overwriting it, otherwise the rest of the chain is lost next_node = current.next current.next = prev prev = current current = next_node # When `current` hits None, `prev` sits on the original tail — our new head return prev def search_matrix(matrix: List[List[int]], target: int) -> bool: """Part 3: search an m x n row-sorted and column-sorted matrix from the top-right corner.""" if not matrix or not matrix[0]: return False num_rows = len(matrix) num_cols = len(matrix[0]) # Start at top-right: moving left decreases values, moving down increases values row = 0 col = num_cols - 1 while row < num_rows and col >= 0: current_val = matrix[row][col] if current_val == target: return True if current_val > target: # Every cell below `(row, col)` in this column is >= current_val > target; rule out column col -= 1 else: # Every cell left of `(row, col)` in this row is <= current_val < target; rule out row row += 1 return False def solve_linked_list_and_matrix( values: List[int], matrix: List[List[int]], target: int ) -> Dict[str, object]: head = build_list(values) # Compute `minimum` BEFORE `reverse_list(head)` mutates `head.next` to None in place! minimum = find_min(head) reversed_head = reverse_list(head) return { "minimum": minimum, "reversed": to_values(reversed_head), "found": search_matrix(matrix, target), }✅ Submit now — all tests should pass.
Intuition & how it works
This question combines two classic mental models:
- Re-coupling train cars without losing the train (linked list reversal): In a singly linked list (a chain of nodes where each node stores a value and one forward
nextreference), reversing in place (modifying the existing nodes directly without allocating a new list) is like unhooking each train car from the car ahead of it and hooking it onto the car behind it. If you unhook the forward coupling first without holding onto the front of the remaining train with your other hand (next_node), the rest of the train rolls away forever. - The staircase walk from the top-right corner (sorted matrix search): Stand at the top-right cell of the grid. Every step left moves to smaller (or equal) numbers, and every step down moves to larger (or equal) numbers. If your current cell is too big, nothing below it in that column can work, so step left; if your current cell is too small, nothing left of it in that row can work, so step down.
Naive choices stumble on each part. Copying list values into an auxiliary array to reverse them wastes O(N) extra node/array space instead of rewiring pointers, and recursive reversal overflows Python's call stack (the memory region storing active function calls) when N = 10,000. For the matrix, scanning every cell costs O(m * n), while starting at the top-left corner (0, 0) gets stuck immediately because both right and down increase values, giving you no way to rule out either direction.
Let's trace Example 1 with values = [5, -2, 9, 4], matrix = [[2, 6, 10], [4, 8, 12], [7, 11, 15]], and target = 8:
- Minimum: Start
smallest = 5, compare with-2(smallest -> -2), then9and4(smalleststays-2). - Reverse:
prev = None, current = 5. Flip5 -> None, then-2 -> 5 -> None, then9 -> -2 -> 5 -> None, then4 -> 9 -> -2 -> 5 -> None. The new head is4, yielding[4, 9, -2, 5]. - Matrix search: Start at top-right
(0, 2) = 10. Since10 > 8, step left to(0, 1) = 6. Since6 < 8, step down to(1, 1) = 8, which matchestargetand returnsTrue.
Complexity
Let N be the number of nodes in the linked list and m x n be the dimensions of the matrix.
find_min: O(N) time and O(1) extra space. We walk each of theNnodes once with a single cursornodeand one integersmallest(every node must be checked because the list is unsorted).reverse_list: O(N) time and O(1) extra space. We visit each node once, reassign its.nextpointer once, and keep only three pointer variables (prev,current,next_node).search_matrix: O(m + n) time and O(1) extra space. Every iteration either decrementscol(at mostntimes before passing0) or incrementsrow(at mostmtimes before reachingm), using only integer indices.- Judge wrapper (
solve_linked_list_and_matrix): Building theN-node linked list fromvaluesand converting the reversed list back to a Python list add O(N) time and O(N) space solely for input/output serialization.
Edge cases
- Single-node list (
[-5]):find_minreturns-5without entering its loop, andreverse_listsets-5.nexttoNoneand returns that same node. - All-positive or all-negative list values: Initializing
smallest = head.valhandles both extremes cleanly, whereas initializing to0would falsely return0on[7, 3]. - Single-row or single-column matrix (
[[1, 3, 5, 7]]or[[1], [2], [5]]): the staircase walk naturally steps straight left across the single row or straight down the single column. - Duplicate numbers in the matrix: we only discard a column when
current_val > target(strictly greater) or a row whencurrent_val < target(strictly smaller), so equal copies oftargetare never discarded. - Target outside the matrix range or inside a gap: targets smaller than
matrix[0][0]walk off the left edge (col == -1), and targets larger thanmatrix[m - 1][n - 1]walk off the bottom edge (row == m), both returningFalse.
Common mistakes
- Overwriting
current.next = prevbefore savingcurrent.next: severs the link to the unreversed suffix on the very first node. - Returning
headinstead ofprevfromreverse_list: after reversal,headis the tail node (head.nextisNone), so returning it losesN - 1nodes. - Calling
reverse_list(head)beforefind_min(head): becausereverse_listmutateshead.next = Nonein place, passing the oldheadtofind_minafterward only inspects a 1-node list! - Starting
search_matrixat(0, 0)or(m - 1, n - 1): at both of those corners, the two adjacent directions change in the same direction, so a comparison cannot eliminate a row or column. - Flattening the matrix for standard 1D binary search:
[[2, 6, 10], [4, 8, 12], [7, 11, 15]]flattens to[2, 6, 10, 4, 8, 12, 7, 11, 15], which is not sorted globally because row 1 starts below row 0's end.
Alternative approaches
- Bottom-left staircase walk: Starting at
(m - 1, 0)is completely symmetric to top-right: moving up decreases values and moving right increases values, giving the exact same O(m + n) time and O(1) space. - Binary search on each row: Binary search repeatedly halves a sorted search interval in O(log n) comparisons. Running it on each of the
mrows takes O(m log n) time and O(1) space, which beats O(m + n) only on very wide, short matrices wheremis tiny andnis huge (for500 x 500,500 + 500 = 1,000steps beats500 * log2(500) ≈ 4,500).
Follow-up questions
- How do the runtime and auxiliary memory usage of in-place pointer reversal scale with a list of length N?
reverse_listruns in O(N) time because the loop visits each of theNnodes exactly once and performs four constant-time pointer assignments per node. It uses O(1) auxiliary space because it rewires existingListNodeobjects in place using only three pointer variables (prev,current,next_node), independent ofN. - How would a recursive implementation of list reversal work, and what call-stack memory trade-offs does it introduce? Recursively reverse
head.nextto obtainnew_head, attach the current node onto the tail of that reversed suffix viahead.next.next = head, and clearhead.next = None(with base casehead is None or head.next is None). However, recursion keeps one active stack frame per node on the call stack, costing O(N) stack space instead of O(1). Because Python does not perform tail-call optimization (reusing the current stack frame for a final recursive call), a10^4-node list exceeds Python's default recursion limit (~1,000 frames) and raisesRecursionError. - Suppose flattening the grid row by row produced one sorted sequence that was then cyclically shifted (for instance, [7, 8, 9, 2, 4, 5]); how could you still locate target in logarithmic time? Treat the
m x ngrid (withK = m * ntotal cells) as a virtual 1D array indexed from0toK - 1, mapping any 1D indexidxtomatrix[idx // n][idx % n]in O(1) time without copying data. Run rotated-sorted-array binary search on[lo, hi]: at every midpointmid, at least one half ([lo..mid]or[mid..hi]) does not cross the wrap-around drop and is therefore sorted, so you test whethertargetfalls within that sorted half's endpoints to discard half the remaining cells each step. With distinct elements this runs in O(log(m * n)) time and O(1) space (if duplicates causefirst == mid_val == last, shrinking bothlo += 1andhi -= 1stays correct though all-duplicate inputs can degrade to O(m * n)).
Follow-up questions
- How do the runtime and auxiliary memory usage of in-place pointer reversal scale with a list of length N?
- How would a recursive implementation of list reversal work, and what call-stack memory trade-offs does it introduce?
- Suppose flattening the grid row by row produced one sorted sequence that was then cyclically shifted (for instance, [7, 8, 9, 2, 4, 5]); how could you still locate target in logarithmic time?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array