Dynamic Array
Remember how a static array is like an egg carton with a fixed number of slots? A dynamic array solves this problem. It's essentially a smart static array that knows how to buy a bigger egg carton when the current one gets full.
Under the hood, it's still just a regular static array. But the dynamic array keeps track of two things:
- Capacity: How many total slots the underlying static array has.
- Size (or Length): How many slots you are actually using right now.
When the Size equals the Capacity, the array is full. If you try to add another item, the dynamic array performs a magical trick called a resize.
← → arrow keys to step · click elements to interact
Dynamic Array: Append & Resize
The Resizing Trick
When the array fills up, it can't just securely claim the memory slot right next to it — that space might be used by another program. Instead, it has to move everything to a new, bigger location. Here is the process:
- Create a brand-new static array that is twice as big as the old one.
- Copy every single item from the old array into the new array, one by one.
- Add the new item you wanted to insert into the first empty slot.
- Delete the old, smaller array so the computer can reuse that memory.
Copying all those items takes \(O(n)\) time. It's an expensive operation!
Amortized Time (The "Almost Always Fast" Rule)
You might think appending to a dynamic array is slow because of the resizing. But because we double the capacity every time we resize, it happens very rarely.
If you add 8 items, you resize when adding the 1st, 2nd, 3rd, 5th, and 9th items. As the array gets huge (say, 1 million items), you have to add another million items before it resizes again! Most of the time, adding an item is an instant \(O(1)\) operation. We call this \(O(1)\) amortized time — which means "it's \(O(1)\) on average over a long period of time."
list, Java's ArrayList, JavaScript's Array, and C++'s std::vector are all dynamic arrays under the hood!Complexity
Custom Dynamic Array with Doubling
Quick check
Continue reading