KatInterview

Adjacent Entries Lookup in a Sorted Catalog

Heaps, Sorting & SearchAuto-graded · 17 test cases
EasyAuto-gradedHeaps, Sorting & Searchbinary-searchsorted-arraybisect

Last updated

Answer batched queries on a sorted list of unique IDs by binary searching for each target and returning its adjacent values, or nulls when the target is absent.

Adjacent Entries Lookup in a Sorted Catalog

A catalog holds unique integer identifiers in strictly ascending order. You must answer a batch of queries against this fixed catalog. Each query names a target identifier and asks for the entries that sit directly next to it in the catalog.

Task

Implement a function that receives:

  • ids: the sorted catalog of unique integers.
  • operations: a list of operation names, one per query. Every valid entry is the string "get_neighbors". If any entry is a different string, raise a ValueError.
  • arguments: a list of argument lists, aligned with operations. For a "get_neighbors" query, arguments[i] is [target_id].

For each query, in order, produce a two-element list [before, after]:

  • before is the catalog entry immediately left of target_id, and after is the entry immediately right of it.
  • If target_id is the first entry, before is None. If it is the last entry, after is None.
  • If target_id does not appear in the catalog, the result is [None, None]. This applies even when the target would fall between two existing entries, or lies below or above all entries. Do not return the surrounding values for a missing target.

Return the list of all result pairs, in the same order as the queries. Each pair must be a list (not a tuple).

Constraints

  • 1 <= len(ids) <= 1,000,000
  • -10^9 <= ids[i] <= 10^9
  • ids is strictly increasing (sorted, no duplicates).
  • len(operations) == len(arguments)
  • Each query should be answered in roughly logarithmic time in len(ids).

Examples

Example 1

Input: sorted_adjacent_lookup([10, 20, 30, 40], ['get_neighbors'], [[20]])

Output: [[10, 30]]

Example 2

Input: sorted_adjacent_lookup([10, 20, 30, 40], ['get_neighbors'], [[5]])

Output: [[None, None]]

Example 3

Input: sorted_adjacent_lookup([10, 20, 30, 40], ['get_neighbors'], [[40]])

Output: [[30, None]]

Hints

Hint 1

Because the catalog is sorted, the neighbors of an entry are simply the items at the adjacent positions. The real work is locating the target's position quickly.

Hint 2

Use binary search (for example `bisect_left`) to find the insertion position, then verify the position is in range and actually holds the target before treating it as found.

Hint 3

Guard the index arithmetic: `ids[-1]` does not raise in Python, so check `index > 0` before reading the left neighbor and `index + 1 < len(ids)` before reading the right one.