Adjacent Entries Lookup in a Sorted Catalog
Heaps, Sorting & SearchAuto-graded · 17 test casesLast 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 aValueError.arguments: a list of argument lists, aligned withoperations. For a"get_neighbors"query,arguments[i]is[target_id].
For each query, in order, produce a two-element list [before, after]:
beforeis the catalog entry immediately left oftarget_id, andafteris the entry immediately right of it.- If
target_idis the first entry,beforeisNone. If it is the last entry,afterisNone. - If
target_iddoes 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^9idsis 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The catalog is strictly sorted with no duplicates, so the neighbors of an entry are just the elements at the adjacent indices. For each query:
- Use binary search (
bisect_left) to find the leftmost positionposwhere the target could be inserted. - Decide whether the target is present. It is absent if
pos == len(ids)(larger than everything) orids[pos] != target(it would slot in between values or before the first one). In that case the answer is[None, None]. - Otherwise the target sits at
pos. The left neighbor isids[pos - 1]ifpos > 0, elseNone. The right neighbor isids[pos + 1]ifpos + 1 < len(ids), elseNone.
Any operation name other than "get_neighbors" raises ValueError.
Why it is correct
bisect_left returns the smallest index such that everything before it is less than the target and everything from it onward is at least the target. If the target exists, it must therefore be at that index, so checking ids[pos] == target is a complete presence test. Since values are strictly increasing and unique, the closest smaller value is at pos - 1 and the closest larger one is at pos + 1. The explicit bounds checks handle the first and last entries, and prevent Python's negative indexing from silently returning the last element when pos == 0.
Complexity
- Time: O(log n) per query, so O(q log n) for q queries.
- Space: O(1) extra per query, plus O(q) for the output.
Reference solution
from bisect import bisect_left
from typing import List, Optional
def sorted_adjacent_lookup(ids: List[int], operations: List[str], arguments: List[List[int]]) -> List[List[Optional[int]]]:
results = []
n = len(ids)
for operation, args in zip(operations, arguments):
if operation != "get_neighbors":
raise ValueError("unsupported operation")
target = args[0]
pos = bisect_left(ids, target)
if pos == n or ids[pos] != target:
results.append([None, None])
else:
before = ids[pos - 1] if pos > 0 else None
after = ids[pos + 1] if pos + 1 < n else None
results.append([before, after])
return results