Snapshot Array

Medium · Design · Array · Hash Table · Binary Search · Design

Problem

Design an array that can take cheap snapshots of its contents and later read any element as it was at any snapshot.

Implement SnapshotArray:

Tests replay a call sequence: the first entry names the class and its constructor arguments, each later entry is a method with its arguments, and calls returning nothing report None.

Examples

Input: ops = ["SnapshotArray","set","snap","set","set","snap","get","get","get"], args = [[3],[1,4],[],[1,8],[2,6],[],[1,0],[1,1],[2,0]]
Output: [None, None, 0, None, None, 1, 4, 8, 0]

Index 1 was 4 at snapshot 0 and 8 at snapshot 1; index 2 was still 0 at snapshot 0.

Input: ops = ["SnapshotArray","snap","snap","get"], args = [[1],[],[],[0,1]]
Output: [None, 0, 1, 0]

Nothing was ever set, so every read is 0.

Constraints

Approaches

Follow-up

What other questions can snapshots answer cheaply? The total of the array at a snapshot needs only a running total recorded at each snap, and counting how often a slot changed between two snapshots needs a change-only history and two binary searches: see the use cases “Total of the array at a snapshot” and “How often a slot changed between two snapshots”.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…