Skip to lesson
0/174 complete
LEARN THE CONCEPTFree forever

Dynamic arrays

Topic 4 of 6 · Arrays and dynamic arrays

What is an array?

An array stores values in a sequence of numbered positions. A position is called an index. Indices usually start at 0: the first value is at index 0, the second at index 1. Knowing the index lets you go directly to that position; finding an unknown value may require checking many positions.

Example: In [4, 8, 15], index 1 contains 8. There are three elements, so the valid indices are 0, 1, and 2. A Python list is a dynamic array: its storage can grow when you append values.

INTERACTIVE WALKTHROUGHMemory model
Full? Make a little room.

A resize copies values into a larger allocation.

CURRENT STORAGEcapacity 4
481516
Append 23 → resize needed
NEW STORAGEcapacity 8
········
PSEUDOCODETrace the idea
if size == capacity:    allocate(capacity * 2)    copy_existing_values()    use_new_storage() storage[size] = 23size += 1
A resize costs O(n). Spare capacity makes later appends cheap.Amortized O(1)
1 / 7

The array is full: size 4, capacity 4.

Interview reasoningWorked exampleTry it yourself
Self-paced learning
Helpful before this chapter

If these ideas are new, begin with:

Understand the idea

Size counts live elements; capacity counts allocated slots. Resizing allocates larger storage, copies references, then switches the backing array. Growth factors vary by runtime; doubling is a teaching policy.

Work through an example

Size 4/capacity 4 grows to capacity 8 before appending 23. Size becomes 5, leaving three spare slots.

Time and space complexity

One resize O(n); geometric growth amortized O(1) append; peak resize storage O(n).

Why it works

Resizing preserves the logical order of all existing elements.

Common mistakes

  • Size and capacity are different.
  • Raw addresses can be invalidated by resizing in low-level languages.

Chapter lab · Python implementation

Arrays make positions directly accessible. Our lab compacts a sorted list: read examines input; write marks the next output slot. Python lists are resizable arrays of references. Fixed-width address diagrams illustrate slots, rather than promising contiguous Python objects.

This shared lab connects the chapter's topics. Follow the current lesson's worked example first, then trace the complete implementation. Additional algorithms described in topic exercises are variations you can implement independently.

def compact_sorted(values):
    write = 0
    for read in range(len(values)):
        if write == 0 or values[read] != values[write-1]:
            values[write] = values[read]
            write += 1
    return write

def transpose(matrix):
    if not matrix:
        return []
    cols = len(matrix[0])
    if any(len(row) != cols for row in matrix):
        raise ValueError('rectangular matrix required')
    return [[matrix[r][c] for r in range(len(matrix))]
            for c in range(cols)]

Run and test the lab

Copy the implementation and these assertions into a Python 3 file and run it. An assertion failure means the actual result differs from the expectation. Add the current topic's exercise and boundary tests to deepen your understanding.

a=[1,1,2,2,3]; k=compact_sorted(a)
assert a[:k]==[1,2,3]
assert compact_sorted([])==0
assert transpose([[1,2,3],[4,5,6]])==[[1,4],[2,5],[3,6]]
assert transpose([])==[]
CHECK YOUR UNDERSTANDING

Does size 4/capacity 8 need a resize for one append?

Course outline
Software Engineer
DSA
THE SOFTWARE ENGINEERING PATH

Data Structures
& Algorithms

Build intuition. Develop a pattern.
Make it your own.

Free course30 chapters
Your progress0%

0 of 174 published lessons complete