DSC 200 (Module C)

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/102

encourage image

There's no tags or description

Looks like no tags are added yet.

103 Terms

1
New cards

Time complexity

How runtime grows as input size n grows.

2
New cards

Space complexity

How memory use grows as input size n grows. Memory is often the real limit.

3
New cards

How do you find the order of growth of code?

Count the loops: how many times the innermost work runs as a function of n.

4
New cards

Single loop over n items

O(n). 10x the data is 10x the work (an if inside doesn't change the order).

5
New cards

Nested loops over n (both over len(data))

O(n^2) quadratic. 10x the data is 100x the work. The most common way code quietly stops scaling.

6
New cards

O(1)

Constant. Example: list index, dict lookup.

7
New cards

O(log n)

Logarithmic. Example: binary search, halving each step.

8
New cards

O(n)

Linear. Example: one pass over the data.

9
New cards

O(n log n)

Linearithmic. Example: a good general-purpose sort.

10
New cards

O(n^2)

Quadratic. Example: compare every pair.

11
New cards

O(2^n)

Exponential. Example: try every subset.

12
New cards

O(n!)

Factorial. Example: try every ordering (travelling salesman brute force).

13
New cards

Three Big-O simplification rules

(1) Drop constants (3n is O(n)). (2) Log base doesn't matter (differ by a constant). (3) Keep only the fastest-growing term (n^2 + 100n + 500 is O(n^2)).

14
New cards

Complexity of a triangular loop (for i in range(n): while j <= i)

1 + 2 + … + n = n(n+1)/2 iterations, so O(n^2).

15
New cards

Complexity of j = n; while j > 0: j = j // 2

O(log n). It halves each step, about log2(n) steps.

16
New cards

Best case vs worst case vs average case

Best = luckiest input (Omega). Worst = unluckiest input, usually quoted because it is the guarantee. Average = typical input.

17
New cards

Big-O vs Theta

Big-O is strictly an upper bound (an O(n) algorithm is also O(n^2)). Theta means growth is exactly that order (tight bound). In practice, O(…) is used to mean Theta, and the course does too.

18
New cards

How to measure scaling empirically

Time the code at several input sizes and plot time vs n on log-log axes. A power law t = c*n^k is a straight line with slope k (about 1 = linear, about 2 = quadratic). Fit with np.polyfit(np.log(sizes), np.log(times), 1)[0].

19
New cards

Effect of a constant factor on a log-log plot

Shifts the line up or down but does not change its slope.

20
New cards

Why is NumPy faster than a Python loop if both are O(n)?

Constant factors: NumPy runs compiled C over contiguous memory. Big-O gives the growth; the constant decides milliseconds vs minutes (why vectorizing matters).

21
New cards

Memory of an n x n float64 matrix

8 bytes x n^2. 1,000 rows is trivial, 50,000 rows is about 20 GB. Check this before an agent materializes all pairwise distances.

22
New cards

Amortized cost

Average cost per operation over many calls when an operation is usually cheap but occasionally expensive. Example: list.append is amortized O(1).

23
New cards

Performance budget

An acceptance criterion with a number, e.g. "full 7M-row file in under 5 s and 2 GB". Observable, so the agent can test it and report PASS/FAIL (unlike "make it faster").

24
New cards

Complexity of an agent session's token cost

Quadratic. The model has no memory so each turn resends the conversation; turn k sends about k turns of tokens, and 1+2+…+turns grows like turns^2. Compact or start fresh to control it; caching lowers price but not the shape.

25
New cards

Why are Python lists and NumPy arrays O(1) to index?

Contiguous memory: element k is at start + k * itemsize, a single address calculation.

26
New cards

Why is growing an array expensive?

The block has fixed size, so growing means allocating a bigger block and copying everything.

27
New cards

Python list over-allocation

Lists keep spare room at the end, so most appends are O(1) and only occasionally copy. Append is amortized O(1).

28
New cards

list.insert(0, x) cost

O(n). Every element shifts. 160,000 insert(0, i) calls are O(n^2).

29
New cards

np.append in a loop

Quietly O(n^2): NumPy arrays don't over-allocate, so each call copies the whole array. Fix: build a Python list, convert to an array once at the end.

30
New cards

pd.concat inside a loop

O(n^2), copies the whole result each time. Fix: collect chunks in a list and call pd.concat(chunks) once (O(n)).

31
New cards

Linked list

Each element is a node holding a reference to the next; the list is just a reference to the head. Nothing is contiguous.

32
New cards

Linked list: index item k

O(n). No address arithmetic, follow k references from the head.

33
New cards

Linked list: add at front

O(1). Make a new node point at the old head, no copying.

34
New cards

Linked list: add_back

O(n) walking to the end, but O(1) if you keep a tail reference. Removing from the back of a singly linked list is still O(n).

35
New cards

Array vs linked list trade-off

Array: O(1) index, O(n) front insert, low memory overhead. Linked list: O(n) index, O(1) front insert, higher overhead (a reference per node). In data science arrays usually win (scan/index more than splice, compiled loops).

36
New cards

Hash table (dict/set)

A hash function turns a key into a number that picks a bucket. Lookup, insert and membership are average O(1), independent of number of items.

37
New cards

Why is x in some_set O(1) but x in some_list O(n)?

A set hashes x and goes straight to its bucket; a list scans every element.

38
New cards

Hashable

A key that is (in practice) immutable, so its hash still points to the right bucket. Tuples work; lists, sets and DataFrames raise TypeError. Use a tuple like (zone, hour) for a compound key.

39
New cards

Hash collisions

Many collisions degrade lookups toward O(n), but Python's hashing makes this rare, so treat dict/set ops as O(1).

40
New cards

Quiet quadratic: membership test against a growing list in a loop

O(n^2); doubling the data roughly quadruples the time. Fix: use a set.

41
New cards

pandas Index is a …

A hash table. After set_index, .loc label lookup is O(1) vs an O(n) boolean scan (df.loc[df["id"] == k]).

42
New cards

What do groupby and merge use under the hood?

Hash tables: groupby hashes group keys to bucket rows; merge hashes join keys to find matches.

43
New cards

Many-to-many join blow-up

merge pairs every matching left row with every matching right row, so rows are the product of matches. Keys [1,1,2] merged with [1,1,2] give 5 rows (1: 2x2=4, 2: 1).

44
New cards

Guard against merge blow-up

pd.merge(…, validate="one_to_one" / "one_to_many" / "many_to_one") raises MergeError instead of silently exploding.

45
New cards

Hash join vs sort-merge join

Hash join: build hash table on one side, probe with other, about O(n + m). Sort-merge: sort both then walk together, about O(n log n + m log m); sort cost vanishes if already sorted.

46
New cards

Stack

LIFO (last in, first out). One access point (top): push, pop, peek. A Python list is already a stack (append, pop(), [-1], all O(1)).

47
New cards

Queue

FIFO (first in, first out). Two access points (front, rear): enqueue, dequeue. Used in autograders, print spoolers, schedulers.

48
New cards

Stack vs queue

Stack: LIFO, one access point, push/pop. Queue: FIFO, two access points, enqueue/dequeue.

49
New cards

Push 10, 20, 30, 0, -30 then pop five times

-30, 0, 30, 20, 10 (a stack reverses order).

50
New cards

Stack use cases

Undo (push each edit, pop the latest) and bracket matching (stack holds unclosed openers; a closer must match the top; leftovers mean unbalanced).

51
New cards

Why is a list a bad queue?

pop(0) is O(n) because every remaining element shifts, so draining is O(n^2). Use collections.deque (O(1) at both ends, popleft()).

52
New cards

Call stack

Each function call pushes a frame (local variables and return location); returning pops it.

53
New cards

Traceback

A printout of the call stack when something went wrong. Read it bottom-up: the last line is the actual error, frames above are the chain of calls.

54
New cards

Recursion

A function calls itself on a smaller version of the problem until a base case it can answer directly.

55
New cards

Python recursion limit

About 1000 frames (sys.getrecursionlimit()); exceeding raises RecursionError. A correct function fails if the depth is too large. Python does not do tail-call optimization.

56
New cards

When to use recursion vs a loop

Recursion for shallow, tree-shaped problems (depth about log n); a loop when depth could grow with the data. Any recursion can be a loop plus a stack you keep yourself.

57
New cards

Flood fill without RecursionError

Use an explicit stack (DFS) or deque (BFS) in a loop, or call scipy.ndimage.label. Recursive version fails because the pending-call chain is thousands deep.

58
New cards

Binary tree

A tree where each node has up to two children.

59
New cards

BST property

For every node, everything in its left subtree is smaller and everything in its right subtree is larger (the whole subtree, not just the immediate child).

60
New cards

BST search cost

The height of the tree. Balanced: O(log n) best; degenerate: O(n) worst. Lecture quiz answer: O(log n) best, O(n) worst.

61
New cards

BST degeneracy

Inserting already-sorted values always goes right, so the tree becomes a line (a linked list in disguise) with height n and O(n) search. Shape depends on insertion order.

62
New cards

Self-balancing trees

Red-black and AVL trees rearrange on insert to keep height O(log n) regardless of insertion order.

63
New cards

B-tree

A shallow, wide balanced tree used by databases and join indexes, tuned so each step reads one disk/memory block. Lookups stay O(log n) whatever the order of arrival.

64
New cards

In-order traversal

Left, node, right. Visits a BST in sorted ascending order. Recursion is fine since depth is about log n.

65
New cards

Pre-order and post-order traversal

Pre-order (node, left, right): used to serialize a tree. Post-order (left, right, node): used to free a tree bottom-up.

66
New cards

Removing a node from a BST

Leaf: detach it. One child: replace node with its child. Two children: replace value with its in-order successor (smallest in right subtree), then remove the successor.

67
New cards

Binary search on a sorted array

Look at the middle; each comparison keeps one half. O(log n), just indices, no pointers. Python: bisect.bisect_left(arr, x). 500,000 items in about 19 steps.

68
New cards

kd-tree

Binary search in space: cycles through dimensions (x, then y, then x…) splitting space so nearest-neighbor search is about O(log n) on average vs scanning all n. scipy.spatial.KDTree: build once, then query.

69
New cards

Great-circle distance trap for kd-trees

A kd-tree uses whatever distance you give it. Flat lat/lon treats longitude +179.5 and -179.5 as 359 degrees apart (dateline) and breaks near poles. Use great-circle distance or project coordinates first.

70
New cards

Heap

A complete binary tree with the heap property. Min-heap: every parent is less than or equal to its children, so the smallest is at the root. Insert and remove-min are O(log n).

71
New cards

Heap insert and remove-min

Insert: put at end, bubble up past larger parent. Remove-min: take root, move last item to root, bubble down past smaller child. Each moves along one root-to-leaf path, O(log n).

72
New cards

Heap array indices

Node i has children at 2i+1 and 2i+2; parent of i is (i-1)//2. Python heapq works on an ordinary list; h[0] is the minimum (array is not fully sorted).

73
New cards

Is [1, 3, 2, 7, 4, 5] a valid min-heap? [1, 2, 5, 3, 4, 0]? [3, 1, 2]?

Only the first is valid. The second has 5 (index 2) with child 0 (index 5). The third has a root larger than its children.

74
New cards

Top-k with a heap

Keep a size-k heap of the best seen: O(n log k) vs O(n log n) for a full sort. heapq.nlargest / nsmallest.

75
New cards

Selection sort

Best O(n^2), worst O(n^2), extra space O(1), not stable. Repeatedly find smallest of the rest and swap into place.

76
New cards

Insertion sort

Best O(n) (nearly sorted), worst O(n^2), extra space O(1), stable. Grows a sorted prefix.

77
New cards

Merge sort

Best and worst O(n log n), extra space O(n), stable. Split in half, sort each, merge. About log n levels with O(n) merging each.

78
New cards

Quick sort

Best O(n log n), worst O(n^2), extra space O(log n), not stable. Partition around a pivot and recurse. Usually fastest in practice.

79
New cards

Heap sort

Best and worst O(n log n), extra space O(1), not stable. Build a heap, pop min n times.

80
New cards

Why can't a comparison sort beat O(n log n)?

It must distinguish n! orderings, each comparison halves the possibilities, so it needs about log2(n!) which is roughly n log n comparisons.

81
New cards

Counting sort and radix sort

Reach O(n) by not comparing (reading digits or buckets), so they only apply to certain kinds of keys.

82
New cards

Stable sort

Equal elements keep their original order. Needed for multi-key sorts (sort by name, then stable sort by city) and reproducible rankings.

83
New cards

Which sort do Python, NumPy and pandas use?

Python sorted/list.sort: Timsort (merge + insertion, stable). NumPy np.sort: introsort (quicksort falling back to heapsort), not stable unless kind="stable". pandas sort_values: NumPy underneath, default quicksort, use kind="stable".

84
New cards

Why can a top-10 table change between runs?

Ties have no guaranteed order under the default unstable quicksort. Use kind="stable" or an explicit tie-breaker like sort_values(["trips", "pulocationid", "dolocationid"]).

85
New cards

Sorting inside a loop anti-pattern

Re-sorting a growing list on every add turns O(n log n) into O(n^2 log n). Use a heap if you need the largest few, or sort once at the end.

86
New cards

External (out-of-core) merge sort

Sort chunks that fit into sorted runs on disk, then stream-merge the runs in one pass with a heap of size = number of runs (heapq.merge). Used by databases and Unix sort.

87
New cards

Graph

Vertices connected by edges. Models road networks, social links, citations, pipeline dependencies. Edges can be undirected or directed. A tree is a graph with no cycles and a root.

88
New cards

Adjacency list

Maps each vertex to a list of neighbors. Space O(|V| + |E|); edge lookup by scanning neighbors. Best for sparse graphs (scipy.sparse does this).

89
New cards

Adjacency matrix

n x n grid. Space always O(n^2); edge lookup O(1). A 1M-vertex sparse graph would need 10^12 entries, almost all zeros.

90
New cards

DFS vs BFS

DFS (depth-first) uses a stack and goes as deep as possible before backtracking. BFS (breadth-first) uses a queue (deque.popleft()) and explores in rings. Same algorithm, different structure holding vertices to visit. Both O(|V| + |E|).

91
New cards

BFS shortest paths

BFS reaches each vertex first via the fewest edges, so it gives shortest paths in an unweighted graph (track a dist dict).

92
New cards

Dijkstra's algorithm

Shortest paths in a weighted graph: like BFS but always pulls the closest unvisited vertex next using a priority queue (heap), O(log n) per step. Use scipy.sparse.csgraph or networkx.

93
New cards

DAG (directed acyclic graph)

Directed graph with no cycles. A dependency is a directed edge. Pipelines, make, package install plans, spreadsheet references, Airflow and Dask are DAGs.

94
New cards

Topological sort

Orders vertices so every edge points forward (every task after its dependencies). That order is the execution plan, found in O(|V| + |E|). graphlib.TopologicalSorter(pipeline).static_order().

95
New cards

What does a topological sort failure mean?

There is a cycle (circular dependency), so no valid order exists. graphlib raises CycleError instead of looping forever.

96
New cards

Intractable problems

No known efficient algorithm as they grow (e.g. travelling salesman, O(n!) brute force; 20 cities about 6e16 routes). Real tools return a heuristic, so "optimal" often means "a sensible heuristic".

97
New cards

Agent pattern: prompt chaining

One agent's output feeds the next. Graph shape: a path (linear DAG).

98
New cards

Agent pattern: routing

A classifier sends work down one branch. Graph shape: a tree.

99
New cards

Agent pattern: parallelization

Split, run at once, combine. Graph shape: fan-out and fan-in (DAG).

100
New cards

Agent pattern: orchestrator-workers

A lead agent hands pieces to workers and merges results. Graph shape: a tree.