Array

Back Home

Category

Category: Sequence types

Topics

Topics: indexing, cache locality, dynamic programming, sliding window

Definition

A contiguous block of memory storing elements of the same type, accessed by integer indices starting from 0.

Use cases

Attributes

Common operations

Operation Time Complexity Description
Access O(1) Get element at index
Search O(n) Linear scan for value
Insert O(n) Shift elements right
Delete O(n) Shift elements left
Append O(1) amortized Add to end (dynamic)

In code

# Static array (fixed size via array module)
from array import array
arr = array('i', [1, 2, 3, 4, 5])

# Access by index
print(arr[2])  # 3

# Modify element
arr[0] = 10

# Python list as dynamic array
nums = [1, 2, 3]
nums.append(4)      # O(1) amortized
nums.insert(0, 0)   # O(n) - shifts all elements

Time complexity

Space complexity

O(n) where n is the number of elements. No auxiliary space beyond the array itself.

Trade-offs

Pros:

Cons:

Variants

When to use vs avoid