KatInterview

Min, Reverse, and Staircase Search in One Function

Linked ListsAuto-graded · 18 test cases
MediumAuto-gradedLinked Listslinked-listreversalmatrix-search

Last 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 with m rows and n columns. 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 in grid.

Task

Return a dictionary with exactly these three keys:

  • "minimum": the smallest integer in values.
  • "reversed": a new list holding the elements of values in reverse order (tail first, head last).
  • "found": True if target appears anywhere in grid, otherwise False.

Rules and edge cases

  • values always has at least one element. Values may be negative or repeated.
  • A single-element list is its own reversal.
  • If grid is empty ([]) or its first row is empty ([[]]), "found" must be False.
  • 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^6
  • 1 <= m, n <= 500 (an empty grid may also be passed and must be handled)
  • Grid entries and target are 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.