Docsity

Data Structures and Algorithms (DSA) in Python – Cheat Sheet & Quick Reference, Cheat Sheet of Computer science

Toggle sidebar
bg1
THE TECH CHEAT SHEET | Data Structures & Algorithms in Python Page 1
COMPUTER SCIENCE / DATA
THE TECH CHEAT SHEET
Data Structures & Algorithms in Python: Core Concepts & Code Snippets
For 1st and 2nd-year CS students and self-paced learners
01 THE OVERVIEW
Six core structures at a glance, with Big O time complexity
STRUCTURE SEARCH INSERT DELETE USE IT WHEN...
Array
Python list; contiguous
memory
O(n) O(n) O(n) You need instant access by index: O(1). Append
at end is O(1) amortised.
Linked List
Nodes chained by pointers O(n) O(1) O(1)
Frequent inserts/removals. Insert at head, or
delete a node you already hold. Finding it first is
O(n).
Stack
LIFO: last in, first out O(n) O(1) O(1) Undo/redo, recursion, bracket matching. Insert =
push, delete = pop (top only).
Queue
FIFO: first in, first out O(n) O(1) O(1) Scheduling, BFS, buffering. Use deque:
list.pop(0) is O(n).
Tree
Binary search tree (BST)
O(log n)
worst O(n)
O(log n)
worst O(n)
O(log n)
worst O(n)
Sorted data, hierarchies, fast lookups. Worst case
happens on a skewed tree; balanced trees (AVL,
red-black) stay O(log n).
Graph
Adjacency list; vertices V,
edges E
O(V+E) O(1) O(V+E)
Networks, maps, dependencies. Search =
BFS/DFS. Insert = add vertex/edge. Delete =
remove vertex (edge removal is O(degree)).
Complexities are typical/average cases. Array and list entries describe inserting or deleting in the middle; at the end of a Python list both are
O(1) amortised for append and pop.
BIG O LADDER: FAST TO SLOW
O(1)
constant O(log n)
halving O(n)
one pass O(n log n)
good sorts O(n^2)
nested loops
Rule of thumb: if your input doubles, O(n) work doubles, O(n^2) work quadruples, and O(log n) work grows by just one
step.
WHICH ONE SHOULD I PICK?
Fast lookup by position -> Array Fast inserts and removals -> Linked List
Undo / backtracking (LIFO) -> Stack Process in arrival order (FIFO) -> Queue
Sorted data, quick search -> Tree (BST) Relationships and networks -> Graph
pf3
pf4

Partial preview of the text

Download Data Structures and Algorithms (DSA) in Python – Cheat Sheet & Quick Reference and more Cheat Sheet Computer science in PDF only on Docsity!

COMPUTER SCIENCE / DATA

THE TECH CHEAT SHEET

Data Structures & Algorithms in Python: Core Concepts & Code Snippets

For 1st and 2nd-year CS students and self-paced learners

THE OVERVIEW

Six core structures at a glance, with Big O time complexity

STRUCTURE SEARCH INSERT DELETE USE IT WHEN...

Array

Python list; contiguous memory

O(n) O(n) O(n)

You need instant access by index: O(1). Append

at end is O(1) amortised.

Linked List

Nodes chained by pointers

O(n) O(1) O(1)

Frequent inserts/removals. Insert at head, or

delete a node you already hold. Finding it first is

O(n).

Stack

LIFO: last in, first out

O(n) O(1) O(1)

Undo/redo, recursion, bracket matching. Insert =

push, delete = pop (top only).

Queue

FIFO: first in, first out

O(n) O(1) O(1)

Scheduling, BFS, buffering. Use deque :

list.pop(0) is O(n).

Tree

Binary search tree (BST)

O(log n)

worst O(n)

O(log n)

worst O(n)

O(log n)

worst O(n)

Sorted data, hierarchies, fast lookups. Worst case

happens on a skewed tree; balanced trees (AVL,

red-black) stay O(log n).

Graph

Adjacency list; vertices V, edges E

O(V+E) O(1) O(V+E)

Networks, maps, dependencies. Search =

BFS/DFS. Insert = add vertex/edge. Delete =

remove vertex (edge removal is O(degree)).

Complexities are typical/average cases. Array and list entries describe inserting or deleting in the middle; at the end of a Python list both are O(1) amortised for append and pop.

BIG O LADDER: FAST TO SLOW

O(1) constant

O(log n) halving

O(n) one pass

O(n log n) good sorts

O(n^2) nested loops

Rule of thumb: if your input doubles, O(n) work doubles, O(n^2) work quadruples, and O(log n) work grows by just one

step.

WHICH ONE SHOULD I PICK?

Fast lookup by position -> Array Fast inserts and removals -> Linked List

Undo / backtracking (LIFO) -> Stack Process in arrival order (FIFO) -> Queue

Sorted data, quick search -> Tree (BST) Relationships and networks -> Graph

02

THE CODE

Initialise and use each structure in 3 lines of Python

ARRAY Python list

arr = [4, 8, 15, 16] # initialise a list (dynamic array) arr.append(23); arr.insert(1, 6) # append O(1) amortised, insert O(n) arr.remove(8); print(arr[2]) # delete by value O(n), index access O(1)

LINKED LIST Singly linked

class Node: # one node = value + pointer to next def init(self, val, nxt=None): self.val, self.next = val, nxt head = Node(0, Node(1, Node(2))) # 0 -> 1 -> 2; prepending is O(1)

STACK LIFO via list

stack = [] # a plain list works as a stack stack.append(1); stack.append(2) # push: O(1) top = stack.pop() # pop returns 2 (last in, first out): O(1)

QUEUE FIFO via deque

from collections import deque # deque = fast double-ended queue q = deque([1, 2, 3]); q.append(4) # enqueue at the back: O(1) first = q.popleft() # dequeue from the front -> 1: O(1)

TREE Binary search tree

class TNode: # BST node: a value + two children def init(s, v): s.val, s.left, s.right = v, None, None root = TNode(8); root.left = TNode(3) # root 8, left child 3, no right child

GRAPH Adjacency list

graph = {'A': ['B','C'], 'B': ['D'], 'C': [], 'D': []} # node -> neighbours graph['C'].append('D') # add edge C -> D: O(1) print('D' in graph['B']) # B -> D edge? O(degree)

PYTHON TIP

Never use list.pop(0) as a queue: it shifts every element (O(n)). Use collections.deque and

popleft() instead.

03

THE PROBLEM SOLVER (CONT.)

Classic interview question #2: Reverse a Linked List

Problem. Given the head of a singly linked list, reverse it and return the new head.

Example. 1 -> 2 -> 3 -> None becomes 3 -> 2 -> 1 -> None.

1 See the goal.^ We do not move values. We flip every node's^ next^ pointer so it points backwards.

2 Use three pointers.^ prev^ (the already-reversed part, starts as None),^ curr^ (the node we are fixing, starts at head), and nxt (a saved link to the rest).

3 Save before you flip.^ Set^ nxt = curr.next^ first. If you flip without saving, the rest of the list is lost.

4 Flip and advance.^ Point^ curr.next^ at^ prev , then move^ prev^ and^ curr^ one step forward.

5 Stop at the end.^ When^ curr^ is None, every node is flipped and^ prev^ is the new head. Time^ O(n) , space O(1).

def reverse_list(head): prev, curr = None, head # prev = reversed part, curr = node to fix while curr: # loop until we run off the end nxt = curr.next # 1. save the rest of the list curr.next = prev # 2. flip the pointer backwards prev = curr # 3. advance prev curr = nxt # 4. advance curr return prev # prev is the new head

TRACE: 1 -> 2 -> 3

Round prev curr List after the flip

start None 1 1 -> 2 -> 3 -> None

1 1 2 None <- 1 2 -> 3

2 2 3 None <- 1 <- 2 3

3 3 None None <- 1 <- 2 <- 3 return prev

INTERVIEW CHECKLIST

1. Clarify the input: can it be empty? negative? duplicated?

2. Brute force first, then name its Big O.

3. Optimise by choosing a better data structure (dict, stack, two pointers).

4. Code cleanly, talking through each line.

5. Test edge cases: empty, single element, duplicates, no answer.