LeetCode solutions

1249. Snapshot Array

My accepted Python solution to LeetCode problem 1249, Snapshot Array, running in 5694ms.

  • Difficulty: Medium
  • Python
  • Runtime 5694ms
  • Memory 46MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 5694ms, memory 46MB, accepted 2026-01-02.

python
class SnapshotArray:

    def __init__(self, length: int):
        self.snap_id = 0
        self.history = [{} for _ in range(length)]

    def set(self, index: int, val: int) -> None:
        self.history[index][self.snap_id] = val

    def snap(self) -> int:
        self.snap_id += 1
        return self.snap_id - 1

    def get(self, index: int, snap_id: int) -> int:
        # Binary search for the latest value at or before snap_id
        history = self.history[index]
        keys = sorted(history.keys())
        
        # Find the largest key <= snap_id
        left, right = 0, len(keys) - 1
        result = 0
        while left <= right:
            mid = (left + right) // 2
            if keys[mid] <= snap_id:
                result = history[keys[mid]]
                left = mid + 1
            else:
                right = mid - 1
        return result


# Your SnapshotArray object will be instantiated and called as such:
# obj = SnapshotArray(length)
# obj.set(index,val)
# param_2 = obj.snap()
# param_3 = obj.get(index,snap_id)

Source