Persistent Data Structure - Problem

A persistent data structure preserves all previous versions of itself when modified. When you update a persistent array, the original version remains unchanged and accessible, while a new version is created with the modification.

Implement a PersistentArray class that supports:

  • set(index, value) - Returns a new version with the element at index set to value
  • get(index) - Returns the element at index in the current version
  • size() - Returns the size of the array

Given a sequence of operations, return the final values of all versions created during the process.

Input & Output

Example 1 — Basic Persistent Operations
$ Input: initial_array = [1,2,3], operations = [["set", 1, 9]]
Output: [[1,2,3], [1,9,3]]
💡 Note: Start with [1,2,3] as Version 1. After set(1,9), create Version 2 as [1,9,3]. Both versions remain accessible.
Example 2 — Multiple Versions
$ Input: initial_array = [5,10], operations = [["set", 0, 7], ["set", 1, 15]]
Output: [[5,10], [7,10], [7,15]]
💡 Note: Version 1: [5,10] → Version 2: [7,10] after set(0,7) → Version 3: [7,15] after set(1,15)
Example 3 — Single Element Array
$ Input: initial_array = [42], operations = [["set", 0, 99]]
Output: [[42], [99]]
💡 Note: Minimal case: original [42] and modified [99] version both stored

Constraints

  • 1 ≤ initial_array.length ≤ 1000
  • 1 ≤ operations.length ≤ 100
  • -106 ≤ array elements ≤ 106
  • Each operation is ["set", index, value] where 0 ≤ index < array.length

Visualization

Tap to expand
INPUTALGORITHMRESULTInitial Array123Operations: [["set", 1, 9]]Goal: Preserve all versions1Create Version 1Store initial array [1,2,3]2Apply set(1, 9)Change index 1 from 2 to 93Create Version 2Store new array [1,9,3]4Return All VersionsBoth versions accessibleVersion HistoryVersion 1:123Version 2:193Final Output:[[1,2,3],[1,9,3]]Key Insight:Persistent data structures preserve all versions while efficiently sharingunchanged data between versions, avoiding expensive full copies.TutorialsPoint - Persistent Data Structure | Path Copying Approach
Asked in
Google 35 Facebook 28 Amazon 25 Microsoft 20
25.8K Views
Medium-High Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen