Min, Reverse, and Staircase Search in One Function
Linked ListsAuto-graded · 18 test casesLast updated
Compute a list's minimum, its reversal, and whether a target exists in a row- and column-sorted matrix, all in one combined function.
Min, Reverse, and Staircase Search
You are given the contents of a singly linked list as a plain Python list, together with a 2D matrix and a target number. Write one function that answers three small questions and returns the answers together in a dictionary.
Inputs
values: a non-empty list of integers, the node values of a singly linked list from head to tail.grid: a 2D list of integers withmrows andncolumns. Every row is sorted in non-decreasing order from left to right, and every column is sorted in non-decreasing order from top to bottom.target: an integer to look for ingrid.
Task
Return a dictionary with exactly these three keys:
"minimum": the smallest integer invalues."reversed": a new list holding the elements ofvaluesin reverse order (tail first, head last)."found":Trueiftargetappears anywhere ingrid, otherwiseFalse.
Rules and edge cases
valuesalways has at least one element. Values may be negative or repeated.- A single-element list is its own reversal.
- If
gridis empty ([]) or its first row is empty ([[]]),"found"must beFalse. - A grid with a single row or a single column is valid and follows the same sortedness rules.
- A target outside the range of values in the grid yields
False. - Do not rely on repeatedly inserting at the front of a Python list to reverse, since that is quadratic. Aim for linear time overall for the list parts and
O(m + n)for the grid search.
Constraints
1 <= len(values) <= 10^4-10^6 <= values[i] <= 10^61 <= m, n <= 500(an empty grid may also be passed and must be handled)- Grid entries and
targetare integers. - Return a dictionary with keys
"minimum","reversed","found".
Examples
Example 1
Input: min_reverse_and_search([3, 1, 4, 2], [[1, 4, 7], [2, 5, 8], [3, 6, 9]], 5)
Output: {'minimum': 1, 'reversed': [2, 4, 1, 3], 'found': True}
Example 2
Input: min_reverse_and_search([10], [[1]], 2)
Output: {'minimum': 10, 'reversed': [10], 'found': False}
Hints
Hint 1
For the minimum, start your running best at the first element rather than at 0, because values can all be negative.
Hint 2
Reversing can be done in a single pass: either build the result by walking the input from the end, or flip node links with prev/curr/next pointers.
Hint 3
For the grid, start at the top-right corner. If the current value is too big, no cell below it in that column can match, so move left; if it is too small, nothing to its left in that row can match, so move down.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The function answers three independent questions, so each is solved on its own.
Minimum. Scan once, keeping the smallest value seen so far. Initialize it with the first element (not 0), since the list is non-empty and may contain only negative numbers.
Reversal. Build a linked list from values, then reverse it in place with three pointers: prev, curr, and nxt. At each step, save curr.next in nxt, point curr.next at prev, then advance prev = curr and curr = nxt. When curr is None, prev is the new head. Convert the nodes back to a Python list for the output.
Grid search. Start at the top-right corner. That cell is the largest in its row and the smallest in its column.
- If it equals
target, the answer isTrue. - If it is larger than
target, everything below it in the column is at least as large, so discard the column by moving left. - If it is smaller than
target, everything to its left in the row is at most as large, so discard the row by moving down.
If the walk leaves the grid, the target is absent. An empty grid returns False immediately.
Why it is correct
- Minimum: after processing
kelements, the running value is the minimum of thosekelements, so after all of them it is the global minimum. - Reversal:
prevalways heads a reversed copy of the nodes already visited andcurrheads the untouched rest. Each iteration moves exactly one node across, and savingnxtfirst ensures no node is lost. - Search: if the target exists, it lies within the remaining rows
row..m-1and columns0..col. Each step either finds it or removes a row or column that provably cannot contain it. When the region is empty, the target is absent.
Complexity
- Minimum:
O(N)time,O(1)extra space. - Reversal:
O(N)time,O(1)pointer space (plusO(N)for building and converting the list to match the I/O format). - Search: at most
m + n - 1steps, soO(m + n)time andO(1)space.
Reference solution
from typing import Dict, List
class _Node:
__slots__ = ("val", "next")
def __init__(self, val, nxt=None):
self.val = val
self.next = nxt
def _build(values):
head = None
for v in reversed(values):
head = _Node(v, head)
return head
def _to_list(head):
out = []
while head:
out.append(head.val)
head = head.next
return out
def min_reverse_and_search(values: List[int], grid: List[List[int]], target: int) -> Dict[str, object]:
head = _build(values)
# Minimum
minimum = head.val
node = head.next
while node:
if node.val < minimum:
minimum = node.val
node = node.next
# In-place reversal
prev, curr = None, head
while curr:
nxt = curr.next
curr.next = prev
prev, curr = curr, nxt
reversed_values = _to_list(prev)
# Staircase search
found = False
if grid and grid[0]:
row, col = 0, len(grid[0]) - 1
while row < len(grid) and col >= 0:
v = grid[row][col]
if v == target:
found = True
break
if v > target:
col -= 1
else:
row += 1
return {
"minimum": minimum,
"reversed": reversed_values,
"found": found,
}