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:

  1. Minimum Node Value (find_min): Traverse the non-empty linked list and compute its smallest integer.
  2. 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.
  3. 2D Monotone Grid Lookup (search_matrix): Given an m x n integer grid matrix in which each row increases or stays flat from left to right and each column increases or stays flat from top to bottom, determine whether target appears 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^6
  • 1 <= m, n <= 500, where m = len(matrix) and n = len(matrix[0])
  • Every row of matrix is sorted in non-decreasing order (matrix[r][c] <= matrix[r][c + 1]).
  • Every column of matrix is sorted in non-decreasing order (matrix[r][c] <= matrix[r + 1][c]).

Step-by-step walkthrough

  1. 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}:

    1. Part 1 (find_min): Given the head of a non-empty singly linked list (1 <= N <= 10^4), return its smallest integer.
    2. Part 2 (reverse_list): Reverse that linked list in place (rewiring existing nodes without creating new ones) and return the new head.
    3. Part 3 (search_matrix): Determine whether target appears in an m x n matrix (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 values as a plain Python list (like [5, -2, 9, 4]), so we build a genuine ListNode chain from values, run find_min and reverse_list on those nodes, and convert the reversed chain back into a list for the judge.
    • Because reverse_list mutates the .next links of the existing nodes in place, we must compute find_min(head) before calling reverse_list(head).
  2. Build the linked list and find its minimum (Part 1)

    A singly linked list is a chain of ListNode objects where each node holds one value (val) and one reference (next) pointing to the following node, ending at None:

    head -> [5 | *-]---> [-2 | *-]---> [9 | *-]---> [4 | None]
    

    To build this chain cleanly in O(N) time without tracking a tail pointer, walk values in reverse and prepend each new node onto the front of head.

    To find the minimum, initialize smallest = head.val (never initialize to 0, which would give the wrong answer when every node is positive!) and advance a node cursor 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 smallest
    
  3. Reverse the linked list in place with three pointers (Part 2)

    To reverse the chain in place, we want every arrow A -> B to flip into A <- B, with the original head now pointing to None.

    Here is the trap: as soon as we overwrite current.next = prev, we cut the link from current to the rest of the unreversed chain! To avoid detaching the remaining suffix, we save next_node = current.next before changing current.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 while loop instead of recursion? With N up to 10,000, a recursive function pushes 10,000 stack frames and crashes against Python's default recursion limit of 1,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 prev
    
  4. Matrix search: why top-left gets stuck, and top-right works (Part 3)

    How can we search an m x n grid 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 m rows 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 if matrix[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
                              larger
    

    At (row, col) = top-right of the remaining candidate grid, the two directions point opposite ways:

    • Everything to the left in row is <= current_val.
    • Everything below in col is >= current_val.

    So a single comparison with target always eliminates an entire row or an entire column:

    1. current_val == target: we found it — return True.
    2. current_val > target: every cell below (row, col) in col is even larger (>= current_val > target), so target cannot be anywhere in column col. Cross out that column (col -= 1).
    3. current_val < target: every cell left of (row, col) in row is even smaller (<= current_val < target), so target cannot be anywhere in row row. Cross out that row (row += 1).
  5. 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 increments row (at most m times) or decrements col (at most n times), the loop runs at most m + n steps:

    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
    
  6. Trace through Example 1

    Let's trace values = [5, -2, 9, 4], matrix = [[2, 6, 10], [4, 8, 12], [7, 11, 15]], and target = 8:

    1. Build & find minimum: head is 5 -> -2 -> 9 -> 4 -> None. Scanning updates smallest from 5 to -2, returning -2.
    2. Reverse: prev advances through 5 -> None, -2 -> 5 -> None, 9 -> -2 -> 5 -> None, and 4 -> 9 -> -2 -> 5 -> None, giving [4, 9, -2, 5].
    3. 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 ]
    
  7. 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:

  1. 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 next reference), 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.
  2. 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), then 9 and 4 (smallest stays -2).
  • Reverse: prev = None, current = 5. Flip 5 -> None, then -2 -> 5 -> None, then 9 -> -2 -> 5 -> None, then 4 -> 9 -> -2 -> 5 -> None. The new head is 4, yielding [4, 9, -2, 5].
  • Matrix search: Start at top-right (0, 2) = 10. Since 10 > 8, step left to (0, 1) = 6. Since 6 < 8, step down to (1, 1) = 8, which matches target and returns True.

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 the N nodes once with a single cursor node and one integer smallest (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 .next pointer 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 decrements col (at most n times before passing 0) or increments row (at most m times before reaching m), using only integer indices.
  • Judge wrapper (solve_linked_list_and_matrix): Building the N-node linked list from values and 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_min returns -5 without entering its loop, and reverse_list sets -5.next to None and returns that same node.
  • All-positive or all-negative list values: Initializing smallest = head.val handles both extremes cleanly, whereas initializing to 0 would falsely return 0 on [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 when current_val < target (strictly smaller), so equal copies of target are 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 than matrix[m - 1][n - 1] walk off the bottom edge (row == m), both returning False.

Common mistakes

  • Overwriting current.next = prev before saving current.next: severs the link to the unreversed suffix on the very first node.
  • Returning head instead of prev from reverse_list: after reversal, head is the tail node (head.next is None), so returning it loses N - 1 nodes.
  • Calling reverse_list(head) before find_min(head): because reverse_list mutates head.next = None in place, passing the old head to find_min afterward only inspects a 1-node list!
  • Starting search_matrix at (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 m rows takes O(m log n) time and O(1) space, which beats O(m + n) only on very wide, short matrices where m is tiny and n is huge (for 500 x 500, 500 + 500 = 1,000 steps beats 500 * 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_list runs in O(N) time because the loop visits each of the N nodes exactly once and performs four constant-time pointer assignments per node. It uses O(1) auxiliary space because it rewires existing ListNode objects in place using only three pointer variables (prev, current, next_node), independent of N.
  • How would a recursive implementation of list reversal work, and what call-stack memory trade-offs does it introduce? Recursively reverse head.next to obtain new_head, attach the current node onto the tail of that reversed suffix via head.next.next = head, and clear head.next = None (with base case head 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), a 10^4-node list exceeds Python's default recursion limit (~1,000 frames) and raises RecursionError.
  • 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 n grid (with K = m * n total cells) as a virtual 1D array indexed from 0 to K - 1, mapping any 1D index idx to matrix[idx // n][idx % n] in O(1) time without copying data. Run rotated-sorted-array binary search on [lo, hi]: at every midpoint mid, at least one half ([lo..mid] or [mid..hi]) does not cross the wrap-around drop and is therefore sorted, so you test whether target falls 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 cause first == mid_val == last, shrinking both lo += 1 and hi -= 1 stays correct though all-duplicate inputs can degrade to O(m * n)).

Follow-up questions

Similar questions

More Fortinet interview questions

All 1 Fortinet questions →