Predecessor and Successor in Sorted IDs

Easy · Coding & Algorithms · Machine Learning Engineer · Technical Screen

Problem Statement

Given a strictly increasing array ids of unique integer record IDs, build a lookup helper NeighborFinder along with the batch runner find_neighbors(ids, operations, arguments) to report the immediate left and right neighbors of requested IDs.

For any target_id passed to get_neighbors(target_id):

  • If target_id occurs in ids at index i:
    • Its predecessor is ids[i - 1] when i > 0, or None when target_id is the very first element (i == 0).
    • Its successor is ids[i + 1] when i + 1 < len(ids), or None when target_id is the very last element (i == len(ids) - 1).
  • If target_id does not occur in ids, both neighbors are None (do not return the elements surrounding where target_id would be inserted).

In find_neighbors(ids, operations, arguments), initialize a single NeighborFinder(ids) and process each "get_neighbors" call (with arguments[k] = [target_id]), returning [predecessor, successor] for every query in order.

Examples

Example 1

Input:
  ids = [105, 210, 340, 500]
  operations = ["get_neighbors"]
  arguments = [[210]]

Output:
  [[105, 340]]

Explanation: 210 sits at index 1 of ids; the entry right before it is 105 and the entry right after it is 340.

Example 2

Input:
  ids = [105, 210, 340, 500]
  operations = ["get_neighbors", "get_neighbors"]
  arguments = [[90], [275]]

Output:
  [[None, None], [None, None]]

Explanation: Neither 90 (smaller than all entries) nor 275 (falling between 210 and 340) exists in ids, so each query returns [None, None].

Example 3

Input:
  ids = [-12, 0, 18, 42]
  operations = ["get_neighbors", "get_neighbors"]
  arguments = [[-12], [42]]

Output:
  [[None, 0], [18, None]]

Explanation: -12 is at index 0 so it has no predecessor and successor 0, whereas 42 is at the final index 3 so its predecessor is 18 and it has no successor.

Constraints

  • 1 <= len(ids) <= 1,000,000
  • -10^9 <= ids[i] <= 10^9
  • ids is strictly sorted in ascending order (ids[i] < ids[i + 1]).
  • 1 <= len(operations) == len(arguments)
  • Each operation is "get_neighbors" with arguments[k] = [target_id] and -10^9 <= target_id <= 10^9.

Step-by-step walkthrough

  1. Understand the problem and missing-target rule

    We are given a strictly increasing list of unique integer IDs (ids[0] < ids[1] < ... < ids[n - 1]) and must answer repeated get_neighbors(target_id) queries:

    • If target_id is present at index idx, return (predecessor, successor) — the element immediately to its left (ids[idx - 1]) and the element immediately to its right (ids[idx + 1]).
    • If target_id sits at the very start (idx == 0) or very end (idx == len(ids) - 1), return None for the missing side.
    • If target_id is not present in ids, return (None, None). Example 2 makes this rule concrete: looking up 90 or 275 in [105, 210, 340, 500] returns (None, None), not (None, 105) or (210, 340).

    The judge calls find_neighbors(ids, operations, arguments) and expects a two-element list [predecessor, successor] for each "get_neighbors" operation.

  2. Why a linear scan is too slow

    The simplest approach is to walk through ids from left to right (or call target_id in ids followed by ids.index(target_id), which performs the exact same left-to-right scan under the hood).

    With up to n = 1,000,000 IDs, a single linear scan checks up to 1,000,000 integers — and every missing target_id is forced to scan all the way to the end! Across thousands of queries, billions of comparisons pile up because a linear scan ignores the biggest clue in the problem statement: ids is already sorted.

  3. Key idea: binary search for the exact index

    Because ids is sorted in ascending order, we can locate target_id with binary search: compare target_id against the middle element, discard the half of the list where target_id cannot possibly live, and repeat. Halving 1,000,000 elements takes at most 20 steps (2^20 = 1,048,576).

    Python's built-in bisect.bisect_left(self.ids, target_id) runs this binary search and returns the first index idx where self.ids[idx] >= target_id (or len(self.ids) if every element in self.ids is smaller than target_id).

    ids = [105, 210, 340, 500]    (indices 0, 1, 2, 3; len = 4)
    
    target_id = 210 -> bisect_left returns idx = 1 -> ids[1] == 210 (FOUND!)
                       neighbors are ids[0] = 105 and ids[2] = 340
    
    target_id = 275 -> bisect_left returns idx = 2 -> ids[2] == 340 != 275 (MISSING between 210 and 340)
                       return (None, None)
    
    target_id = 600 -> bisect_left returns idx = 4 -> idx == len(ids) (MISSING past the end)
                       return (None, None)
    

    Once we confirm target_id is at idx, its neighbors sit right next door at idx - 1 and idx + 1 — with one critical Python gotcha to guard against:

    • When idx == 0, idx - 1 is -1. In Python, self.ids[-1] does not raise an error — it silently returns the last element of the list! Always check if idx > 0: before reading self.ids[idx - 1].
  4. Implement NeighborFinder

    In __init__, we copy ids with list(ids) so that if the caller later mutates their own list, our internal list stays sorted. In get_neighbors, notice the order of the two conditions in if idx == len(self.ids) or self.ids[idx] != target_id: — checking idx == len(self.ids) first guarantees Python stops early before ever attempting self.ids[len(self.ids)].

    class NeighborFinder:
        def __init__(self, ids: List[int]) -> None:
            # ids: strictly increasing list of unique integer IDs, e.g. [105, 210, 340, 500].
            # Store a copy so later changes to the caller's list cannot break sorted order.
            self.ids: List[int] = list(ids)
    
        def get_neighbors(self, target_id: int) -> Tuple[Optional[int], Optional[int]]:
            # Phase 1: Binary search for the leftmost index idx where self.ids[idx] >= target_id.
            idx = bisect.bisect_left(self.ids, target_id)
    
            # Phase 2: Confirm target_id is actually present. Check idx == len(self.ids) first
            # so targets larger than every ID never trigger an out-of-range read on self.ids[idx].
            if idx == len(self.ids) or self.ids[idx] != target_id:
                return (None, None)
    
            # Phase 3: Read adjacent neighbors safely. We must check idx > 0 explicitly because
            # self.ids[-1] in Python would silently wrap around and return the last element!
            predecessor: Optional[int] = None
            if idx > 0:
                predecessor = self.ids[idx - 1]
    
            successor: Optional[int] = None
            if idx + 1 < len(self.ids):
                successor = self.ids[idx + 1]
    
            return (predecessor, successor)
    
  5. Wire up the runner and trace all five cases

    find_neighbors initializes one NeighborFinder and converts each (predecessor, successor) tuple into the [predecessor, successor] list format expected by the judge.

    def find_neighbors(
        ids: List[int], operations: List[str], arguments: List[List[int]]
    ) -> List[List[Optional[int]]]:
        # Build NeighborFinder once and answer every get_neighbors query in O(log n) time.
        finder = NeighborFinder(ids)
        results: List[List[Optional[int]]] = []
    
        for operation, args in zip(operations, arguments):
            if operation == "get_neighbors":
                target_id = args[0]
                predecessor, successor = finder.get_neighbors(target_id)
                results.append([predecessor, successor])
            else:
                raise ValueError(f"Unknown operation: {operation}")
    
        return results
    

    Let's trace ids = [105, 210, 340, 500] across interior, boundary, and missing-target positions:

    target_id  bisect_left  Present check               predecessor        successor           Result
    ---------  -----------  --------------------------  -----------------  ------------------  ------------
    210        idx = 1      ids[1] == 210 (yes)         idx > 0 -> 105     1 + 1 < 4 -> 340    [105, 340]
    90         idx = 0      ids[0] == 105 != 90 (no)    -                  -                   [None, None]
    500        idx = 3      ids[3] == 500 (yes)         idx > 0 -> 340     3 + 1 < 4 (false)   [340, None]
    275        idx = 2      ids[2] == 340 != 275 (no)   -                  -                   [None, None]
    600        idx = 4      idx == len(ids) (no)        -                  -                   [None, None]
    
  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import bisect
    
    
    class NeighborFinder:
        def __init__(self, ids: List[int]) -> None:
            # ids: strictly increasing list of unique integer IDs, e.g. [105, 210, 340, 500].
            # Store a copy so later changes to the caller's list cannot break sorted order.
            self.ids: List[int] = list(ids)
    
        def get_neighbors(self, target_id: int) -> Tuple[Optional[int], Optional[int]]:
            # Phase 1: Binary search for the leftmost index idx where self.ids[idx] >= target_id.
            idx = bisect.bisect_left(self.ids, target_id)
    
            # Phase 2: Confirm target_id is actually present. Check idx == len(self.ids) first
            # so targets larger than every ID never trigger an out-of-range read on self.ids[idx].
            if idx == len(self.ids) or self.ids[idx] != target_id:
                return (None, None)
    
            # Phase 3: Read adjacent neighbors safely. We must check idx > 0 explicitly because
            # self.ids[-1] in Python would silently wrap around and return the last element!
            predecessor: Optional[int] = None
            if idx > 0:
                predecessor = self.ids[idx - 1]
    
            successor: Optional[int] = None
            if idx + 1 < len(self.ids):
                successor = self.ids[idx + 1]
    
            return (predecessor, successor)
    
    
    def find_neighbors(
        ids: List[int], operations: List[str], arguments: List[List[int]]
    ) -> List[List[Optional[int]]]:
        # Build NeighborFinder once and answer every get_neighbors query in O(log n) time.
        finder = NeighborFinder(ids)
        results: List[List[Optional[int]]] = []
    
        for operation, args in zip(operations, arguments):
            if operation == "get_neighbors":
                target_id = args[0]
                predecessor, successor = finder.get_neighbors(target_id)
                results.append([predecessor, successor])
            else:
                raise ValueError(f"Unknown operation: {operation}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of looking up a job ID in a sorted street directory to see who lives directly on either side: instead of reading every address starting from the top of page 1, you open straight to the middle of the book, check whether your target ID is smaller or larger than that middle entry, and throw away the half where it cannot be. Repeating that halving step is binary search (an algorithm that locates a value in a sorted array by cutting the remaining search range in half on every comparison). Once you land on the exact index idx of target_id, its immediate predecessor and successor are simply sitting at idx - 1 and idx + 1.

Why does the naive approach fall short? Checking if target_id in self.ids: or calling self.ids.index(target_id) scans the list element by element from index 0. With 1,000,000 IDs, a single lookup can take 1,000,000 comparisons — and every missing ID has to scan the entire list before giving up. Binary search shrinks 1,000,000 items down to at most 20 comparisons per query.

Here is how bisect.bisect_left (which returns the leftmost index idx where ids[idx] >= target_id, or len(ids) if none exists) handles three representative queries on ids = [105, 210, 340, 500]:

ids = [105, 210, 340, 500]   (indices 0..3, len = 4)

1. target_id = 210 -> bisect_left gives idx = 1 -> ids[1] == 210 (match!)
                      left neighbor ids[0] = 105, right neighbor ids[2] = 340 -> (105, 340)
2. target_id = 500 -> bisect_left gives idx = 3 -> ids[3] == 500 (match at right edge!)
                      left neighbor ids[2] = 340, idx + 1 == 4 is out of bounds -> (340, None)
3. target_id = 275 -> bisect_left gives idx = 2 -> ids[2] == 340 != 275 (missing!)
                      stop immediately -> (None, None)

Complexity

Let n be len(ids) and q be the number of get_neighbors queries.

  • NeighborFinder.__init__ — O(n) time and O(n) space: Copying ids with list(ids) touches each of the n integers once so external changes to the caller's list cannot corrupt our sorted order. (Storing a direct reference self.ids = ids would make initialization O(1) time and O(1) extra space if immutability is guaranteed.)
  • get_neighbors(target_id) — O(log n) time and O(1) extra space: bisect_left halves the n-element range at each step (at most ~20 comparisons for n = 1,000,000), followed by O(1) boundary checks and array reads at idx - 1 and idx + 1.
  • Total across q queries — O(n + q log n) time and O(n + q) space: One O(n) setup, q logarithmic lookups, and O(q) space to hold the output list returned by find_neighbors.

Edge cases

  • Target is the very first element (idx == 0): There is no element to its left, so predecessor is None and successor is ids[1] (Example 3: -12, or None if len(ids) == 1).
  • Target is the very last element (idx == len(ids) - 1): successor is None and predecessor is ids[idx - 1] (Example 3: 42).
  • Single-element list (ids = [7]): Whether target_id is 7 (present with no left or right neighbor) or 6 (missing), the result is (None, None).
  • Target missing in all three positions: Smaller than ids[0] (Example 2: 90), between two IDs (Example 2: 275), or larger than ids[-1] (600 where idx == len(ids)). All three return (None, None).
  • Negative IDs and boundary extremes (-10^9 and 10^9): Python integers have arbitrary precision and compare naturally across negative, zero, and positive values.

Common mistakes

  • Forgetting if idx > 0: before self.ids[idx - 1]: When idx == 0, idx - 1 evaluates to -1, and Python's negative indexing silently returns the last item of self.ids instead of raising an IndexError!
  • Checking self.ids[idx] != target_id before idx == len(self.ids): Python's or uses short-circuit evaluation (meaning if the left condition is True, Python skips evaluating the right condition). Putting idx == len(self.ids) first prevents self.ids[len(self.ids)] from crashing when target_id exceeds every ID.
  • Returning insertion-point neighbors for a missing ID: If target_id = 90 is missing from [105, 210, 340, 500], bisect_left returns 0, which sits next to 105 — but the specification requires (None, None) whenever target_id itself is absent.
  • Calling if target_id not in self.ids: before binary search: in on a Python list performs an O(n) linear scan, completely erasing the O(log n) speedup of binary search.
  • Off-by-one infinite loops in manual binary search: Mixing inclusive (hi = len(ids) - 1) and half-open (hi = len(ids)) bounds — such as writing while lo <= hi: with hi = mid — can loop forever when lo == hi or read past the end of the list.

Alternative approaches

  • Hand-written binary search (O(log n) query, O(n) space): If an interviewer asks you to implement bisect_left without importing bisect, keep a half-open search window [lo, hi) where every index before lo is strictly < target_id and every index from hi onward is >= target_id:

python def lower_bound(ids: List[int], target_id: int) -> int: lo = 0 hi = len(ids) while lo < hi: mid = (lo + hi) // 2 if ids[mid] < target_id: lo = mid + 1 else: hi = mid return lo

  • Hash map from id -> index (O(1) average query, O(n) extra space): Building pos = {value: i for i, value in enumerate(ids)} in __init__ lets get_neighbors look up idx = pos.get(target_id) in O(1) average time instead of O(log n). The trade-off is several times higher memory usage (a hash table stores keys, values, and spare buckets on top of the ids list) and losing the ability to find nearby IDs for missing targets if requirements later change.

Follow-up questions

  • How would you design this lookup service if the sorted ID array were too large to hold in RAM? Store the sorted IDs on disk as fixed-width 8-byte binary integers so record k lives at exact byte offset 8 * k, allowing binary search to jump directly to any middle record in O(log n) disk seeks. Better yet, build a small in-memory sparse index (a compact array storing every 1,024th ID and its disk block number): binary search the sparse index in RAM with zero disk I/O, read just one 8 KB block from disk, and binary search inside that block (reading one adjacent record if idx lands on a block boundary). This layered block layout is the core idea behind a B-tree (a disk-optimized search tree used by databases to answer sorted lookups in 2–3 page reads).
  • How would you extend the method to return the k nearest neighbors rather than only the immediate left and right IDs? First clarify whether "nearest" means k elements on each side by position or k elements with the smallest numeric distance |id - target_id|. For k on each side, slice self.ids[max(0, idx - k) : idx] and self.ids[idx + 1 : idx + 1 + k] in O(log n + k) time. For the k numerically closest IDs, run a two-pointer search (maintaining left = idx - 1 and right = idx + 1 moving outward from idx), repeatedly picking whichever side has the smaller distance target_id - ids[left] versus ids[right] - target_id until k neighbors are collected in O(log n + k) time.
  • How could you speed up throughput if millions of lookup requests hit the same unchanging ID list? If RAM allows, precomputing a dict mapping id -> index cuts each lookup from O(log n) (~20 comparisons) to O(1) average time. In Python, function-call and loop overhead often dominates CPU time, so accepting queries in batches and calling numpy.searchsorted(ids_array, target_batch) runs all binary searches inside tight compiled C loops. Finally, because the list is completely read-only, multiple worker processes can answer queries in parallel while sharing a single physical copy of the array in RAM via a memory-mapped file (mmap) (an OS feature that maps a disk file directly into multiple processes' virtual memory without duplicating RAM).

Follow-up questions

Similar questions

More Ziprecruiter interview questions

All 3 Ziprecruiter questions →