??? ?? ??????? ?????? ????
??? ?? ??????? ?????? ????
How do
data structures: a deep dive
dynamic
arrays
work?
1 2 3 4
1 2 3 4
Find more
interview tips ->
neetcode.io
Overview
Dynamic arrays are arrays that can be resized.
Most languages have a default size for dynamic arrays. For example,
Java has a default size of 10 and C++ has a default size of 4 upon
initialization.
Find more
interview tips ->
neetcode.io
Insertion
With a static array, when the array becomes full, we can no longer
insert elements. With dynamic arrays, as soon as the length of the
array reaches the capacity, the size of the array doubles to
accommodate new insertions.
Capacity refers to the number of elements that the array can hold.
length = 3
capacity = 3
New insertion
1 2 3
1 2 3 4
Find more
interview tips ->
neetcode.io
Resizing
Resizing is a key feature of dynamic arrays, making them "dynamic."
How do we resize
Allocate a new array with twice the original capacity
Copy the elements from the old array to the new one
Update the reference to point to the new array.
capacity = 6
length = 0
capacity = 3
1 2 3 length = 3
capacity = 6
1 2 3 length = 3
Copy the elements
1+2+4+8+⋯+n
The largest resize accounts
for more work than all
previous resizes combined.
Find more
interview tips ->
neetcode.io
Join a million people
preparing for coding
interviews
neetcode.io