TExcelTAD

DSA Arrays

An array stores values one after another in a single block of memory. Because every slot has the same size, the computer can jump straight to slot i by computing start address + i × slot size. That is why reading a[i] takes the same time whether i is 0 or 999,999.

Python's list behaves like a dynamic array: it is a contiguous block of references that grows automatically. In this course we use lists as arrays, and we implement the algorithms with indexes and loops instead of built-in helpers, so you see every step.

Basic operations and their cost

Operation Python Cost Why
Read / write by index a[i], a[i] = x O(1) address arithmetic
Append at the end a.append(x) O(1) on average spare capacity at the end
Insert at the front or middle a.insert(i, x) O(n) later items shift right
Remove from the middle a.pop(i) O(n) later items shift left
Search for a value x in a O(n) may check every slot
Length len(a) O(1) stored with the list
python · try it yourself
temps = [18, 21, 19, 24, 22]
print(temps[3])          # direct access
temps[0] = 17            # overwrite in place
temps.append(20)         # add at the end
print(temps, len(temps))
24
[17, 21, 19, 24, 22, 20] 6

Walking through an array

Most array algorithms are loops over indexes. Here we find the lowest value and its position, which the sorting algorithms will need:

python · try it yourself
temps = [18, 21, 15, 24, 22, 15]

min_index = 0
for i in range(1, len(temps)):
    if temps[i] < temps[min_index]:
        min_index = i
print(f"lowest {temps[min_index]} at index {min_index}")
lowest 15 at index 2

Because we use < and not <=, the first occurrence of the lowest value wins (index 2, not 5). Small details like this decide whether a sorting algorithm is stable, a property you'll meet soon.

Inserting means shifting

Inserting into the middle of an array is expensive, because every later value must move one slot to the right. Let's do it by hand to see the work:

python · try it yourself
def insert_at(arr, index, value):
    arr.append(None)                     # make room at the end
    moves = 0
    for i in range(len(arr) - 1, index, -1):
        arr[i] = arr[i - 1]              # shift one slot right
        moves += 1
    arr[index] = value
    return moves

data = [10, 20, 30, 40, 50]
moves = insert_at(data, 1, 15)
print(data, f"({moves} values moved)")
moves = insert_at(data, len(data), 60)
print(data, f"({moves} values moved)")
[10, 15, 20, 30, 40, 50] (4 values moved)
[10, 15, 20, 30, 40, 50, 60] (0 values moved)

Inserting at index 1 moved four values; inserting at the end moved none. Removing from the front has the same problem in reverse, which is why we will use linked lists or collections.deque for queues.

Two-dimensional arrays

A table or grid is an array of arrays. grid[row][col] first picks a row, then a column:

python · try it yourself
seats = [
    [0, 1, 1, 0],
    [1, 1, 0, 0],
    [0, 0, 0, 1],
]
taken = 0
for row in range(len(seats)):
    for col in range(len(seats[row])):
        taken += seats[row][col]
print("rows:", len(seats), "cols:", len(seats[0]))
print("taken seats:", taken)
print("row 1, col 2 is", "taken" if seats[1][2] else "free")
rows: 3 cols: 4
taken seats: 5
row 1, col 2 is free

Note: Create a grid with a comprehension, [[0] * cols for _ in range(rows)]. The shortcut [[0] * cols] * rows makes every row the same list, so changing one cell changes a whole column.

Arrays and sorting

Sorted arrays unlock fast algorithms: binary search finds a value in O(log n), duplicates sit next to each other, and the minimum and maximum are at the ends. The next eight lessons show different ways to sort, each with an animation and a Python implementation. Here is a preview of what "sorted" means in code:

python · try it yourself
def is_sorted(arr):
    return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))

print(is_sorted([3, 8, 8, 12]))
print(is_sorted([3, 9, 4]))
print(is_sorted([]))
True
False
True

Test yourself

Why is reading a[i] from an array O(1)?

  1. Arrays are always small
  2. The address of slot i is computed directly from the start address
  3. Python caches every value
  4. The array is searched from both ends

How many values must move when you insert at index 0 of an array with 8 values?

  1. 0
  2. 1
  3. 7
  4. 8

What is wrong with grid = [[0] * 3] * 2?

  1. It raises an error
  2. Both rows are the same list object
  3. It creates 3 rows of 2
  4. Nothing