DSA Tutorial menu

DSA Arrays

An array stores items one after another, and each item has a numbered position called an index.

What is an Array?

Think of a row of lockers numbered 0, 1, 2, 3. Each locker holds one item. If you know the number, you can open that locker directly.

In memory, an array's items sit next to each other. That is why the computer can jump to any index in one step.

In Python, the built-in list works as a dynamic array: it can grow and shrink.

Example

python
marks = [72, 85, 64, 90]
print(marks[0])
print(marks[3])
print(len(marks))

marks[2] = 70
print(marks)
Output
72
90
4
[72, 85, 70, 90]

Costs of Array Operations

OperationPythonBig OWhy
Read by indexa[i]O(1)Jump straight to the position
Change by indexa[i] = xO(1)Same reason
Add at the enda.append(x)O(1) on averageSpace is usually ready
Insert at the start or middlea.insert(0, x)O(n)Items must shift right
Delete from the start or middlea.pop(0)O(n)Items must shift left
Search for a valuex in aO(n)May check every item

Inserting at the front of a big list is slow because every item has to move. If you often add at the front, use a different structure, such as a deque (see the queues lesson).

Traversing an Array

Traversal means visiting every item. This finds the smallest and largest marks in one pass:

Example

python
marks = [72, 85, 64, 90, 58]

lowest = marks[0]
highest = marks[0]
for m in marks:
    if m < lowest:
        lowest = m
    if m > highest:
        highest = m

print("Lowest:", lowest)
print("Highest:", highest)
print("Average:", sum(marks) / len(marks))
Output
Lowest: 58
Highest: 90
Average: 73.8

This is O(n): one loop over the data.

Reversing an Array In Place

Swap the first and last items, then move both pointers towards the middle. This uses no extra list, so the extra space is O(1).

Example

python
def reverse(items):
    left = 0
    right = len(items) - 1
    while left < right:
        items[left], items[right] = items[right], items[left]
        left += 1
        right -= 1

nums = [1, 2, 3, 4, 5]
reverse(nums)
print(nums)
Output
[5, 4, 3, 2, 1]

This two-pointer technique appears in many interview problems.

Two-dimensional Arrays

A list of lists works like a table, with rows and columns. Here are the marks of three students in two subjects:

Example

python
results = [
    [80, 75],
    [62, 90],
    [55, 68],
]
print(results[1][1])

for row in results:
    print(sum(row))
Output
90
155
152
123

results[1][1] means row 1, column 1 (counting from zero).

Exercise

Exercise

Why is reading arr[500] from an array O(1)?

Learn DSA with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp