Data Structures & Algorithms · Module 2 · Lesson 11 min read

Arrays

What is an array?

A collection of items stored next to each other in memory, each with an index starting at 0. Python's list is a dynamic array that grows automatically.

Costs of common operations

OperationExampleBig O
Read or write by indexa[3]O(1)
Append at the enda.append(x)O(1) on average
Insert or delete at the start or middlea.insert(0, x)O(n): items shift
Search for a valuex in aO(n)
Pop from the enda.pop()O(1)

Why index access is instant

The computer calculates the address directly: start + index × size. No searching needed.

Common techniques

  • Prefix sums: precompute running totals so any range sum is O(1).
  • In-place updates: change the array without making a copy, saving memory.
  • Two pointers (next lesson) and sliding window (Unit 12).

2D arrays (matrices)

grid[row][col], used for game boards, images and maps. Create them with grid = [[0] * cols for _ in range(rows)]. ⚠️ Never [[0] * cols] * rows: every row would be the same list.

💡 When a problem says "subarray", think contiguous items; for those, prefix sums or a sliding window usually help.

Example

Python
nums = [3, 1, 4, 1, 5, 9, 2, 6]

# Prefix sums: any range total in O(1)
prefix = [0]
for x in nums:
    prefix.append(prefix[-1] + x)

def range_sum(i, j):            # sum of nums[i..j]
    return prefix[j + 1] - prefix[i]

print(range_sum(2, 5))          # 4 + 1 + 5 + 9 = 19

# Reverse in place with O(1) extra space
i, j = 0, len(nums) - 1
while i < j:
    nums[i], nums[j] = nums[j], nums[i]
    i, j = i + 1, j - 1
print(nums)                     # [6, 2, 9, 5, 1, 4, 1, 3]

# A 3×3 grid done right
grid = [[0] * 3 for _ in range(3)]
grid[1][1] = 5
print(grid)                     # [[0, 0, 0], [0, 5, 0], [0, 0, 0]]