Data Structures Every Programmer Must Know

Why Data Structures Matter

Data structures determine how you store and access information. The right structure can make code 1000x faster. The wrong one can crash your app.

Arrays and Lists

# O(1) access by index
fruits = ["apple", "banana", "cherry"]
print(fruits[1])  # banana

# O(n) search
if "banana" in fruits:
    print("Found!")

Dictionaries (Hash Maps)

# O(1) average lookup
user = {"name": "Alice", "age": 30, "city": "NYC"}
print(user["name"])  # Alice

# Counting occurrences
words = ["cat", "dog", "cat", "bird", "dog", "cat"]
count = {}
for word in words:
    count[word] = count.get(word, 0) + 1
print(count)  # {'cat': 3, 'dog': 2, 'bird': 1}

Stacks (LIFO)

stack = []
stack.append("a")  # push
stack.append("b")
stack.append("c")
top = stack.pop()  # c (last in, first out)

Queues (FIFO)

from collections import deque
queue = deque()
queue.append("first")
queue.append("second")
first = queue.popleft()  # first (first in, first out)

Big O Complexity

Structure Access Search Insert
Array O(1) O(n) O(n)
Dictionary N/A O(1) O(1)
Stack O(n) O(n) O(1)
Queue O(n) O(n) O(1)

Trees

Trees are hierarchical. Binary Search Trees give O(log n) operations when balanced. Used in file systems, databases, and game AI.

Choosing the Right Structure

  • Need fast lookup by key? Use a dictionary
  • Need ordered access? Use an array or list
  • Need undo/redo? Use a stack
  • Need first-come-first-served? Use a queue

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top