Query a Versioned Array
TruefoundrySoftware Engineer · OnsiteLast updated
This problem tests your ability to design a data structure that supports efficient state snapshots and point queries, specifically focusing on space-time trade-offs.
Versioned Array Design
Design a data structure VersionedArray that supports an array of a fixed length N (initialized to all zeros) and allows for versioning of its state. The structure must implement the following methods:
set(index, value, version): Sets the value atindexfor a specificversion. Versions are non-decreasing integers.get(index, version): Returns the value atindexat the specifiedversion. If no explicitsetwas performed for that index at or before theversion, it should return the value from the most recent previous version.
Requirements
- Initialize the array with
lengthN where all values are initially 0 at version 0. set(index, value, version): Update the array such that subsequentgetcalls forversionand higher reflect this change until the next update for that index.get(index, version): Fetch the value at the givenindexas it existed at the providedversion.
Example
v = VersionedArray(5)
v.set(1, 10, 1)
v.set(1, 20, 2)
print(v.get(1, 1)) # Output: 10
print(v.get(1, 2)) # Output: 20
print(v.get(1, 0)) # Output: 0
Constraints
indexis within[0, N-1].versionis a non-negative integer.- Aim for sub-linear time complexity for
getoperations relative to the total number of updates.
Edge Cases
- Accessing an index that was never set.
- Accessing a version lower than any update version.
- Performing multiple
setoperations for the same index at the same version (last update wins).
Hints
Hint 1
Consider storing a list of (version, value) pairs for each index in the array.
Hint 2
For each index, the list of versioned updates will be sorted by version; use binary search to quickly find the latest value at or before a given version.
Hint 3
If you want to optimize memory, consider only storing updates; if an index was never updated, it implicitly remains zero.
Follow-up questions
- How would you optimize the space complexity if the array is very sparse (few indices are ever updated)?
- What are the time and space complexities for `set` and `get` operations in your current design?
- How would you modify the design if you needed to support a `delete_version(version)` operation?
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.