Design Dynamic Array

Design a Dynamic Array (aka a resizable array) class, such as an ArrayList in Java or a vector in C++.

Your Dynamic Array should support the following operations:

  • DynamicArray(int capacity) will initialize an empty array with a capacity of capacity, where capacity > 0.
  • int get(int i) will return the element at index i. Assume that index i is valid.
  • void set(int i, int n) will set the element at index i to n. Assume that index i is valid.
  • void pushback(int n) will push the element n to the end of the array.
  • int popback() will pop and return the element at the end of the array. Assume that the array is non-empty.
  • void resize() will double the capacity of the array.
  • int getSize() will return the number of elements in the array.
  • int getCapacity() will return the capacity of the array.

If we insert an element when the size of the array is equal to the capacity, the resize() function should be called.

1class DynamicArray:
2 def __init__(self, capacity: int):
3 self.capacity = capacity
4 self.length = 0
5 self.arr = [0] * capacity
6
7 def get(self, i: int) -> int:
8 return self.arr[i]
9
10 def set(self, i: int, n: int) -> None:
11 self.arr[i] = n
12
13 def pushback(self, n: int) -> None:
14 if self.length == self.capacity:
15 self.resize()
16 self.arr[self.length] = n
17 self.length += 1
18
19 def popback(self) -> int:
20 if self.length > 0:
21 self.length -= 1
22 return self.arr[self.length]
23
24 def resize(self) -> None:
25 self.capacity = 2 * self.capacity
26 new_arr = [0] * self.capacity
27 for i in range(self.length):
28 new_arr[i] = self.arr[i]
29 self.arr = new_arr
30
31 def getSize(self) -> int:
32 return self.length
33
34 def getCapacity(self) -> int:
35 return self.capacity
length
0
0
0
1
0
2
capacity=3
Step 1 / 7
Step 1:
Start with capacity=3 and length=0 (no elements are “active” yet).
Pointers: length=0
Focus: default
capacity=3