[JS] | Beats 98% 🚀 | Stuck on runtime errors? read this detailed approach
Intuition\nThe fisrt thought is to create an array and fill it with zeros. DON\'T DO THAT, as it will probably lead to memory-related runtime errors becouse of 
# Intuition\nThe fisrt thought is to create an array and fill it with zeros. DON\'T DO THAT, as it will probably lead to memory-related runtime errors becouse of many copies (snapshots):\n![Screenshot 2023-06-11 104118.png](https://assets.leetcode.com/users/images/f328b71d-4757-4188-b2e8-a3189eadd10c_1686490990.0145652.png)\n\nreading the description carefully gives us a hint:\n> `SnapshotArray(int length)` initializes an array-like data structure with the given length. Initially, each element equals 0.\n\ntwo important insights on this quote:\n***array-like data structure***: It dont have to be an array. As we will not be iterating over the array, and only acccessing indexes directly, we could use a hash-map-like structure, such as a pure js object, where the index is the key that holds a value\n***"Initially, each element equals 0"***: - DOOON\'T. It does\'t has to be. As we will be using a key-value data structure, the absense of a value in our data structure can be seen as an empty space, so we return `0` when `data[idx] === undefined`.\n\n# Approach\nEven doing the optimizations above, you can still fall into one or another runtime error. This could happen if you are **always** copying the current data when `snap()` is called.\n\nYou have to copy *only* when the data changed between an `snap()` call and another. \n\nWhen `snap()` is called without `set()` in between, the new snapshot will be the same as the previous one, so it can just point to the last snapshot doing something like `snaps.push(snaps[snaps.length-1])`, instead of copying the current data.\n\nWe will track changes with a simple flag `hasChanges`, that we sets to true everytime that `set()` is called.\n\nSo lets go to the code:\n\n\n# Code\n```\nvar SnapshotArray = function(length) {\n    this.curr = {};\n    this.snaps = [];\n    this.hasChanges = false;\n};\n\nSnapshotArray.prototype.set = function(idx, val) {\n    this.curr[idx] = val;\n    this.hasChanges = true;\n};\n\nSnapshotArray.prototype.snap = function() {\n    if (this.hasChanges || this.snaps.length  === 0) {\n        this.snaps.push({...this.curr});\n    } else {\n        this.snaps.push(this.snaps[this.snaps.length - 1])\n    }\n    this.hasChanges = false;\n    return this.snaps.length - 1;\n};\n\nSnapshotArray.prototype.get = function(idx, snap_id) {\n    return this.snaps[snap_id][idx] || 0\n};\n````\n\n![Screenshot 2023-06-11 110334.png](https://assets.leetcode.com/users/images/016a80dd-63cc-4018-bf27-7b79faa9ae70_1686492632.1015654.png)\n\n
['Hash Table', 'TypeScript', 'JavaScript']