Find the Closest Version by Date
AmazonSoftware Engineer · OnsiteLast updated
This problem tests your ability to efficiently search through chronologically ordered records and handle binary search logic with custom comparison rules.
Problem Statement
You are working on a document versioning system at Amazon. You are given a list of Version objects, where each object contains a version_id (a string) and a created_at (a Unix timestamp). The list is sorted by created_at in ascending order.
Implement a function find_closest_version(versions, target_date) that returns the version_id of the version that was active or closest to the target_date. If two versions are equally close to the target_date, return the one with the earlier created_at timestamp. If the target_date is earlier than any existing version, return the version_id of the earliest version.
Function Signature
class Version:
def __init__(self, version_id, created_at):
self.version_id = version_id
self.created_at = created_at
def find_closest_version(versions: list[Version], target_date: int) -> str:
pass
Constraints
1 <= len(versions) <= 10^50 <= created_at, target_date <= 10^12- The
versionslist is pre-sorted bycreated_at.
Examples
Example 1:
versions = [Version('v1', 100), Version('v2', 200), Version('v3', 300)]target_date = 250- Output:
'v2'(200 is closer to 250 than 300 is, or equally spaced, we return the earlier one if needed, but here 200 is clearly closer).
Example 2:
versions = [Version('a', 10), Version('b', 20)]target_date = 5- Output:
'a'(Target is before the first version).
Edge Cases
- The
target_dateis exactly equal to one of thecreated_attimestamps. - The
target_dateis larger than any timestamp in the list. - The list contains only one version.
Hints
Hint 1
Since the list is sorted by timestamp, consider using binary search to achieve O(log n) time complexity.
Hint 2
During your binary search, keep track of the closest version found so far by comparing the absolute difference between `target_date` and the current `created_at`.
Hint 3
Remember to handle the case where the target date falls outside the bounds of the list's timestamps.
Follow-up questions
- How would you modify your solution if the input list was not sorted?
- If the system receives thousands of queries per second for the same dataset, what caching strategy would you implement?
- How would you handle a scenario where multiple versions share the exact same `created_at` timestamp?
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.