Dynamic Array
Data StructureLinearAn array that grows on its own. Python list works this way. Build one with a fixed-size backing array.
append 1, 2, 3 → capacity grows 1 → 2 → 4a[1] → 2
- Use a fixed array
a, withn= items used andcap= slots. - On append, if
n == cap, it means full. Copy into a new array twice as big. - Write at slot
nand add 1 ton. - On pop, shrink to half when only a quarter is used.
append O(1) amortized · pop O(1) amortized · get O(1) · insert in middle O(n)
- Doubling, not adding a fixed amount, is what makes append O(1) amortized.
- Shrink at 1/4, not 1/2, or a push and pop at the edge would resize every time.
- Bounds check the index.
class DynArray:
def __init__(self):
self.cap, self.n, self.a = 1, 0, [None]
def append(self, x):
if self.n == self.cap:
self._resize(2 * self.cap)
self.a[self.n] = x
self.n += 1
def pop(self):
if self.n == 0:
raise IndexError("pop from empty array")
self.n -= 1
x, self.a[self.n] = self.a[self.n], None
if 0 < self.n <= self.cap // 4:
self._resize(self.cap // 2)
return x
def __getitem__(self, i):
if not 0 <= i < self.n:
raise IndexError(i)
return self.a[i]
def _resize(self, cap):
b = [None] * cap
b[:self.n] = self.a[:self.n]
self.a, self.cap = b, cap