Find Neighboring Records by Identifier
ZiprecruiterMachine Learning Engineer · Technical ScreenLast updated
This question tests the ability to manage ordered sequences and perform O(log n) lookups to retrieve adjacent elements in a dataset.
Problem Statement
You are given a list of unique numerical identifiers representing job posting IDs, sorted in ascending order. You need to design a service that, given a specific target ID, returns the ID immediately preceding it (the predecessor) and the ID immediately following it (the successor).
If the target ID is not present in the list, the service should return None for both values. If the target is the first or last element, return None for the missing neighbor.
Implement the class NeighborFinder with the following structure:
class NeighborFinder:
def __init__(self, ids: list[int]):
# Initialize with a sorted list of unique integers
pass
def get_neighbors(self, target_id: int) -> tuple[int | None, int | None]:
# Returns (predecessor, successor) for the target_id
pass
Constraints
1 <= len(ids) <= 1,000,000-10^9 <= ids[i] <= 10^9- The input list is strictly sorted.
Examples
Example 1:
Input: ids = [10, 20, 30, 40], target_id = 20
Output: (10, 30)
Example 2:
Input: ids = [10, 20, 30, 40], target_id = 5
Output: (None, None)
Example 3:
Input: ids = [10, 20, 30, 40], target_id = 40
Output: (30, None)
Hints
Hint 1
Since the input list is sorted, consider using binary search to find the target_id in O(log n) time.
Hint 2
If the target_id is found at index i, the neighbors are simply at indices i-1 and i+1, provided they are within bounds.
Hint 3
If the target_id is not present, you can use the bisect_left module or standard binary search logic to determine where the target would have been inserted.
Follow-up questions
- How would your implementation change if the input list was extremely large and couldn't fit into memory?
- What if the requirement changed to return the k closest neighbors instead of just the immediate ones?
- How would you optimize the `get_neighbors` method if you had to perform millions of queries on the same static list?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.