Dynamic lists

An array that grows by itself · Part of Lists, stacks and hash

Key idea

Practice

6 questions · about 3 min

Explained step by step

Dynamic array

A list is an ordered collection of elements where you can read, change, add, remove and walk without worrying about capacity. It can be built with a linked list, which grows by itself, or with an array, which has a fixed size. Since you almost never know in advance how much data will arrive, a dynamic array is used: an array that grows by itself when it fills up. Most languages come with one ready to use.

A dynamic list keeps 3 numbers: the capacity, which is the size of the array inside; the size, which is how many elements there really are; and the growth factor, which says how much it grows when full. If the capacity is 10 and element 11 arrives, an array of 20 is requested (factor 2), the 10 are copied and the new one is added. After that there's room for 9 more without copying anything.

A fixed array and a dynamic list store data the same way: in an adjacent block of memory. The difference is that the list keeps count of how many elements it has and grows on its own. In exchange, it usually reserves extra slots, which take memory even when empty. For algorithms where the size is known in advance, a fixed array is enough; when it isn't, the dynamic list is the practical choice.

Besides reading, adding and removing, lists let you join 2 lists and sort them. Joining appends all of the second's elements to the end of the first: it costs as much as the second's length. Sorting costs O(n log n) with the methods languages provide. Once sorted, you can use fast techniques like binary search or 2 pointers, which walk the list from both ends.

To build a simple dynamic list, 3 pieces are enough: an array with an initial capacity, for example 10; a variable counting how many elements there are, which says where the list ends and when it's full; and the growth rule, for example doubling the capacity and moving everything when full. Real languages' lists choose those numbers carefully to balance memory and speed.

Amortized cost

Since it's built on an array, a dynamic list reads and updates by position in O(1). Adding at the end is amortized O(1): there's almost always room and it costs 1 step, and once in a while everything has to be copied, but spread over all the additions the average is still constant. Inserting or removing in the middle is still O(n), just like an array, because the others have to shift.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

An array that grows by itself