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_idoccurs inidsat indexi:- Its predecessor is
ids[i - 1]wheni > 0, orNonewhentarget_idis the very first element (i == 0). - Its successor is
ids[i + 1]wheni + 1 < len(ids), orNonewhentarget_idis the very last element (i == len(ids) - 1).
- Its predecessor is
- If
target_iddoes not occur inids, both neighbors areNone(do not return the elements surrounding wheretarget_idwould 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^9idsis strictly sorted in ascending order (ids[i] < ids[i + 1]).1 <= len(operations) == len(arguments)- Each operation is
"get_neighbors"witharguments[k] = [target_id]and-10^9 <= target_id <= 10^9.
Step-by-step walkthrough
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 repeatedget_neighbors(target_id)queries:- If
target_idis present at indexidx, return(predecessor, successor)— the element immediately to its left (ids[idx - 1]) and the element immediately to its right (ids[idx + 1]). - If
target_idsits at the very start (idx == 0) or very end (idx == len(ids) - 1), returnNonefor the missing side. - If
target_idis not present inids, return(None, None). Example 2 makes this rule concrete: looking up90or275in[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.- If
Why a linear scan is too slow
The simplest approach is to walk through
idsfrom left to right (or calltarget_id in idsfollowed byids.index(target_id), which performs the exact same left-to-right scan under the hood).With up to
n = 1,000,000IDs, a single linear scan checks up to1,000,000integers — and every missingtarget_idis 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:idsis already sorted.Key idea: binary search for the exact index
Because
idsis sorted in ascending order, we can locatetarget_idwith binary search: comparetarget_idagainst the middle element, discard the half of the list wheretarget_idcannot possibly live, and repeat. Halving1,000,000elements takes at most20steps (2^20 = 1,048,576).Python's built-in
bisect.bisect_left(self.ids, target_id)runs this binary search and returns the first indexidxwhereself.ids[idx] >= target_id(orlen(self.ids)if every element inself.idsis smaller thantarget_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_idis atidx, its neighbors sit right next door atidx - 1andidx + 1— with one critical Python gotcha to guard against:- When
idx == 0,idx - 1is-1. In Python,self.ids[-1]does not raise an error — it silently returns the last element of the list! Always checkif idx > 0:before readingself.ids[idx - 1].
- When
Implement NeighborFinder
In
__init__, we copyidswithlist(ids)so that if the caller later mutates their own list, our internal list stays sorted. Inget_neighbors, notice the order of the two conditions inif idx == len(self.ids) or self.ids[idx] != target_id:— checkingidx == len(self.ids)first guarantees Python stops early before ever attemptingself.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)Wire up the runner and trace all five cases
find_neighborsinitializes oneNeighborFinderand 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 resultsLet'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]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 andO(n)space: Copyingidswithlist(ids)touches each of thenintegers once so external changes to the caller's list cannot corrupt our sorted order. (Storing a direct referenceself.ids = idswould make initializationO(1)time andO(1)extra space if immutability is guaranteed.)get_neighbors(target_id)—O(log n)time andO(1)extra space:bisect_lefthalves then-element range at each step (at most~20comparisons forn = 1,000,000), followed byO(1)boundary checks and array reads atidx - 1andidx + 1.- Total across
qqueries —O(n + q log n)time andO(n + q)space: OneO(n)setup,qlogarithmic lookups, andO(q)space to hold the output list returned byfind_neighbors.
Edge cases
- Target is the very first element (
idx == 0): There is no element to its left, sopredecessorisNoneandsuccessorisids[1](Example 3:-12, orNoneiflen(ids) == 1). - Target is the very last element (
idx == len(ids) - 1):successorisNoneandpredecessorisids[idx - 1](Example 3:42). - Single-element list (
ids = [7]): Whethertarget_idis7(present with no left or right neighbor) or6(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 thanids[-1](600whereidx == len(ids)). All three return(None, None). - Negative IDs and boundary extremes (
-10^9and10^9): Python integers have arbitrary precision and compare naturally across negative, zero, and positive values.
Common mistakes
- Forgetting
if idx > 0:beforeself.ids[idx - 1]: Whenidx == 0,idx - 1evaluates to-1, and Python's negative indexing silently returns the last item ofself.idsinstead of raising anIndexError! - Checking
self.ids[idx] != target_idbeforeidx == len(self.ids): Python'soruses short-circuit evaluation (meaning if the left condition isTrue, Python skips evaluating the right condition). Puttingidx == len(self.ids)first preventsself.ids[len(self.ids)]from crashing whentarget_idexceeds every ID. - Returning insertion-point neighbors for a missing ID: If
target_id = 90is missing from[105, 210, 340, 500],bisect_leftreturns0, which sits next to105— but the specification requires(None, None)whenevertarget_iditself is absent. - Calling
if target_id not in self.ids:before binary search:inon a Pythonlistperforms anO(n)linear scan, completely erasing theO(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 writingwhile lo <= hi:withhi = mid— can loop forever whenlo == hior 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 implementbisect_leftwithout importingbisect, keep a half-open search window[lo, hi)where every index beforelois strictly< target_idand every index fromhionward 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): Buildingpos = {value: i for i, value in enumerate(ids)}in__init__letsget_neighborslook upidx = pos.get(target_id)inO(1)average time instead ofO(log n). The trade-off is several times higher memory usage (a hash table stores keys, values, and spare buckets on top of theidslist) 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
klives at exact byte offset8 * k, allowing binary search to jump directly to any middle record inO(log n)disk seeks. Better yet, build a small in-memory sparse index (a compact array storing every1,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 ifidxlands 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
knearest neighbors rather than only the immediate left and right IDs? First clarify whether "nearest" meanskelements on each side by position orkelements with the smallest numeric distance|id - target_id|. Forkon each side, sliceself.ids[max(0, idx - k) : idx]andself.ids[idx + 1 : idx + 1 + k]inO(log n + k)time. For theknumerically closest IDs, run a two-pointer search (maintainingleft = idx - 1andright = idx + 1moving outward fromidx), repeatedly picking whichever side has the smaller distancetarget_id - ids[left]versusids[right] - target_iduntilkneighbors are collected inO(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
dictmappingid -> indexcuts each lookup fromO(log n)(~20 comparisons) toO(1)average time. In Python, function-call and loop overhead often dominates CPU time, so accepting queries in batches and callingnumpy.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
- How would you design this lookup service if the sorted ID array were too large to hold in RAM?
- How would you extend the method to return the `k` nearest neighbors rather than only the immediate left and right IDs?
- How could you speed up throughput if millions of lookup requests hit the same unchanging ID list?
Similar questions
- Real-Time Restaurant Vote Leaderboard
- Transactional Device Feature CLI Processor
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance