Snapshot Versioning of Array (Multithreading)

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-04-02

Problem Statement

Design and implement a thread-safe snapshot array that supports concurrent reads, writes, and versioning. The system should allow multiple threads to update an array while preserving consistent snapshots of its state at different points in time.


Functional Requirements


1.<span></span>Initialization
2.<span></span>Initialize an array of size N with all elements set to 0.
3.<span></span>Operations
4.<span></span>set(index, value) → Update an element in the current version.
5.<span></span>snapshot() → Take a snapshot of the array, returning a version_id.
6.<span></span>get(index, version_id) → Retrieve the value of an element at a given snapshot version.
7.<span></span>Versioning
8.<span></span>Each snapshot should represent an immutable, consistent view of the array.
9.<span></span>Reads on old versions must still work after future writes.
10.<span></span>Snapshots should be memory-efficient (avoid copying the whole array each time).


Concurrency Requirements


1.<span></span>Multiple threads may call set, get, and snapshot simultaneously.
2.<span></span>Writers must not block readers querying historical snapshots.
3.<span></span>Snapshots must be atomic: once a snapshot is created, it must not reflect partial writes.
4.<span></span>Ensure correctness in the presence of race conditions (e.g., two threads setting different indices at the same time).


Constraints


1.<span></span>Array size: up to 10^7.
2.<span></span>Number of snapshots: up to 10^5.
3.<span></span>High concurrency: support 100+ threads performing mixed operations.
4.<span></span>Efficiency targets:
5.<span></span>set → O(1) amortized.
6.<span></span>get → O(log V) or better, where V = number of snapshots.
7.<span></span>snapshot → O(1).
8.<span></span>Memory usage should grow only with the number of changes, not N × versions.


Example

<div><div>text</div><div>CopyEdit</div><div>Thread-1: set(0, 5) // array becomes [5,0,0,0,0]</div><div>Thread-2: v1 = snapshot() // snapshot v1: [5,0,0,0,0]</div><div>Thread-3: set(0, 10) // array becomes [10,0,0,0,0]</div><div>Thread-4: v2 = snapshot() // snapshot v2: [10,0,0,0,0]</div><div>Thread-5: get(0, v1) → 5</div><div>Thread-6: get(0, v2) → 10</div></div>


Deliverables


1.<span></span>A thread-safe implementation of the snapshot array.
2.<span></span>Tests with multiple threads performing concurrent reads/writes/snapshots.
3.<span></span>Benchmark results comparing throughput under increasing numbers of threads.
4.<span></span>Documentation explaining the synchronization strategy (locks, lock-free design, or MVCC-like approach).


Solution

Comments