Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Created December 27, 2023 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save primaryobjects/ff33faac5bd5f0c8d207bc767fbb0e4f to your computer and use it in GitHub Desktop.
Save primaryobjects/ff33faac5bd5f0c8d207bc767fbb0e4f to your computer and use it in GitHub Desktop.
Design Dynamic Array (Resizable Array) https://neetcode.io/problems/dynamicArray
class DynamicArray {
/**
* @constructor
* @param {number} capacity
*/
constructor(capacity) {
this.data = new Array(capacity);
this.num_elements = 0;
}
/**
* @param {number} i
* @returns {number}
*/
get(i) {
return this.data[i];
}
/**
* @param {number} i
* @param {number} n
* @returns {void}
*/
set(i, n) {
this.data[i] = n;
}
/**
* @param {number} n
* @returns {void}
*/
pushback(n) {
if (this.num_elements === this.data.length) {
this.resize();
}
this.set(this.num_elements++, n);
}
/**
* @returns {number}
*/
popback() {
const val = this.get(this.num_elements - 1);
this.set(this.num_elements - 1, undefined);
this.num_elements--;
return val;
}
/**
* @returns {void}
*/
resize() {
const newArr = new Array(this.data.length * 2);
for (let i=0; i<this.data.length; i++) {
newArr[i] = this.get(i);
}
this.data = newArr;
}
/**
* @returns {number}
*/
getSize() {
return this.num_elements;
}
/**
* @returns {number}
*/
getCapacity() {
return this.data.length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment