COMPSCI220 Cheatsheet · Algorithms and Data Structures

University of Auckland · Cheatsheet for the final exam. Semester Two examination period, 29 October – 16 November 2026 (check your personal exam timetable). Full COMPSCI220 study guide →

A4 landscape · two sides · 6 columns · revision and self-testCOMPSCI220 · S2 2026
COMPSCI220
Algorithms and Data Structures
School of Computer Science · University of Auckland · Undergraduate Stage 2
COMPSCI220 cheatsheet QR code – open the full COMPSCI220 study guide
Full guide + ask Sia
about COMPSCI220
SIDE 1/2   DEFINITIONS · FORMULAS · DECISION RULES · COMPARISONS Exam revision sheet S2 2026 · v2 · 2026-10-25

0 · Exam Mapcourse.json · brief

15%Tests 35%Final 50%
ComponentWeightFormat / role
Practical Component15%quiz, written/programming assignments, tutorial presentations; must be passed
Tests35%two midterm tests; theory component
Final Examination50%comprehensive theory assessment covering the full course

Permitted materials: not confirmed for this offering in the course materials we hold — check the exam instructions on the LMS. Source: BRIEF.md

The pass structure has three checks: pass the practical component, pass the theory component formed by tests and examination, and pass overall. Treat the final as a course-wide test of moving between representation → trace → correctness → growth.

inputformtracewhycorrectcount +qualifycorrect output alone ≠ proofand does not establish scale
Course-wide answer route: representation, operation trace, correctness condition, counted growth.

Priority grid — what a complete response contains

ClusterObservable workBoundary to say aloud
Asymptoticsdefine n; count; exhibit c,n₀; verify inequalityupper bound need not be tight
Correctnessstate invariant; show state before/after a stepexamples do not prove correctness
Sortingtrace subproblems and merge; justify recurrencecheck worst case, memory, stability
Treesexecute insertion/removal; show affected pathrunning time follows actual height
Hashingcalculate location and α; trace each collisionexpected cost needs assumptions

Six-line answer audit

1 InputHave I named the representation and input-size variable?
2 StateCan a marker see the relevant state before the operation?
3 ConditionIs the comparison, invariant or ordering rule explicit?
4 UpdateDid I show exactly what changes and what stays fixed?
5 CostDoes the growth claim follow from counted work or height?
6 LimitDid I name the assumption that prevents overclaiming?

1 · Asymptotic AnalysisC1 · final theory

Asymptotic analysis studies how time or space grows with input size while ignoring fixed implementation constants. Name the input variable n and the counted operation before naming a class.

Big-O definition · bound proofT(n) ∈ O(g(n)) ⇔ ∃ c,n₀ > 0:
0 ≤ T(n) ≤ c·g(n) for every n ≥ n₀

ClaimWhat must appearBoundary
T ∈ O(g)exhibit c and n₀; verify the inequalityeventual upper bound
Correct loopstate invariant; trace state change; connect to resulttests alone are not proof
Scales as claimedoperation count + input variableconstants abstracted away
count T(n)choose g(n)find c,n₀prove ≤state upperbound onlyupper bound need not be tight
Source figure redrawn: asymptotic object → Big-O evidence → qualified growth claim.

Correctness via a loop invariant

A loop invariant is true before and after each iteration and supports the result. Before executing, record the relevant state; for each operation show the branch or iteration, state before/after, and what output depends on it. Check a normal, boundary and invalid input, but keep the logical distinction: matching examples do not constitute proof.

Trace fieldQuestion it answersWhat not to omit
ObjectWhat value, structure or cost is analysed?input variable and representation
ControlWhich branch, iteration or call follows?the condition selecting it
Before / afterWhat state transition occurred?unchanged state that preserves the rule
InvariantWhat proposition survives every iteration?connection from preserved fact to result
Operation countHow does work grow with n?the operation actually being counted

Safe conclusion language

Bound: “For the exhibited positive constants, the inequality holds from n₀ onward, so T(n) has the stated eventual upper bound.” Correctness: “The stated proposition is preserved by the iteration and supports the required result.” These are different claims; proving either one does not silently prove the other.

2 · Sorting + RecurrencesC2 · trace + cost

A comparison sort bases ordering decisions on comparisons between keys. Trace the subproblems and merge, then justify the cost. Keep correctness/order properties separate from time and memory claims.

Merge-sort recurrence · cost responseT(n) = 2T(n/2) + c·n ∈ Θ(n log n)

Term / propertyMeaning in the answer
2T(n/2)two half-size recursive subproblems
c·nlinear merge work; not another recursive call
Θ(log n) levelsrepeated halving to base cases
Θ(n) per levellinear work across a complete level
stabilityequal keys retain their relative order
n · merge cnn/2n/2basebasebasebase
Source recurrence figure redrawn: logarithmically many levels, linear work across each level.

Decision rule

If the prompt asks for a trace, show subproblem states and the merge result. If it asks for cost, identify both recursive and non-recursive terms, then connect levels × work per level. If it asks whether the sort is suitable, check worst-case input, memory cost and required stability; asymptotic or average performance does not erase them.

Line of workingWhat to writeSelf-check
Inputthe sequence and comparison keyare equal keys distinguishable as records?
Divideeach half-size subproblemdoes the trace match 2T(n/2)?
Combinelinear merge work across the levelis cn kept outside the recursive term?
Levelsrepeated halving gives logarithmic depthis work per whole level linear?
Order propertyrelative order of equal-key recordsis the required stability preserved?
ConclusionΘ(n log n) for this relationshiphave worst case and memory been ignored?

Stability test: attach identity to records sharing a key, then inspect their relative order after the merge. A sorted sequence can still fail a stability requirement. Keep the stability observation alongside, not inside, the recurrence calculation.

3 · Heaps + Search TreesC3 · operation trace

A heap is a complete-tree structure with parent–child ordering for extreme-priority operations. A binary search tree orders every node against keys in its left and right subtrees. These structures answer different questions: a heap exposes an extreme; a search tree organises ordered search.

Zero-based array heap · index traceleft(i) = 2i + 1    right(i) = 2i + 2
candidate index only → verify index < array length

StructureShape / order evidenceCost control
Heapcomplete-tree shape + parent–child orderpath through its height
BSTleft/right subtree key relationactual tree height
Degenerate BSTinsertion order stretches the treedo not claim logarithmic height
ileft2i+1right2i+2
Source heap figure redrawn: formulas locate candidates; the array bound decides whether nodes exist.

Trace insertion or removal

  1. State the representation and ordering rule.
  2. Show the affected index/node before and after each move.
  3. Stop only when the required relation is restored.
  4. Relate the number of moves to structural height.
Operation evidenceHeapBST
Starting statearray length, index, parent–child orderroot and left/right key relation
Next movecompare only existing candidate childrenfollow comparison into one subtree
Changed stateshow each moved entry and indexshow link/node affected by insert/remove
Stop rulerequired parent–child relation restoredtarget found or insertion position reached
balancedins. chain
Tree height is the mechanism: logarithmic-operation claims require logarithmic height.

4 · Hashing + CollisionsC4 · table-state trace

A hash function deterministically maps a key to an integer used to choose a table location. A collision means multiple keys map to the same location; a collision strategy must determine how insertion and retrieval proceed.

Load factor · occupancy responseα = n / m
n = stored entries · m = table capacity

StageRecord explicitlyReason
Hashkey → computed locationshows deterministic placement
Collisionoccupied location + competing keysactivates the stated strategy
Resolveevery location examined or link followedmakes expected access cost traceable
Loadstored entries / capacityconnects occupancy to collision pressure
keyhashlocationcollisiontraceplace /findα describes occupancy;it is not a probe count
Source hash-table figure redrawn: location, collision and resolution must be shown as one trace.

What the conclusion may say

Expected collision and lookup behaviour depends on the collision method and hash-quality assumptions. Constant expected lookup is conditional: it does not mean every operation is constant in the worst case. Chaining and open addressing deteriorate differently, so do not interpret α without the stated collision method.

Wrong shortcutRepair
α = occupied buckets / entriesα = stored entries / capacity
“hashing is O(1)”state expected claim + hashing/resizing assumptions
show final table onlyshow collision path and resulting state

Trace ledger — one row per inserted key

ColumnRecordWhy it matters
Keythe current key onlypreserves insertion order
Hash resultinitial table locationseparates mapping from resolution
Observed stateempty, matching key, or collisionshows why the next rule fires
Resolution pathevery slot examined or link followedmakes access work visible
Resulting tablestate after this insertionbecomes the next row’s input

5 · Traversal + ComponentsC5 · reachability trace

A graph representation records vertices and edges, for example with adjacency lists or a matrix. Breadth-first search explores vertices in nondecreasing unweighted distance from a start vertex.

First BFS discovery · distance traced(v) = d(u) + 1 when v is first discovered from u
record predecessor u · enqueue v once

s · 011222layers= edgecounts
Source BFS figure redrawn: first discovery fixes the shortest unweighted edge count.
NeedDoQualification
Traversalshow queue/discovery order from given adjacency orderorder can change with adjacency order
Distanceassign predecessor distance + 1 on first discoveryunweighted edge count
Componentcollect all vertices reachable under direction rulesmaximal reachable set

Connected component: a maximal set of vertices mutually reachable by paths under the graph’s direction rules. A different adjacency order may change the discovery tree or predecessor, but not the shortest unweighted edge counts.

6 · Weighted OptimisationC6 · compare objectives

Relaxation · shortest-path traced(v) ← min{d(v), d(u)+w(u,v)}
update predecessor only when the candidate is cheaper

shortest-pathtreepaths from a sourceminimise path weightminimum spanningtreeconnect every vertexminimise total weightdifferent objectivesare not interchangeable
Source weighted-graph figure redrawn: shortest-path and spanning-tree objectives differ.
ObjectDefinition / condition
Shortest pathminimum total edge weight among paths allowed by the model and algorithm assumptions
MSTminimum-total-weight acyclic set connecting every vertex in a connected undirected graph
Dijkstra conditionnon-negative edge weights for its finality claim
https://www.asksia.ai/cheatsheet/auckland-compsci220 · Full COMPSCI220 study guide →
Forward this to your tutorial group · Shared by ________
AskSiav2 · 2026-10-25
Semester Two examination period, 29 October – 16 November 2026 (check your personal exam timetable).
Check your exam instructions on the LMS for what you may bring; use this sheet to revise and self-test.
COMPSCI220
Algorithms and Data Structures · Self-Test Drills
Answer path · judgement cards · classic traps · exam-morning plan
COMPSCI220 cheatsheet QR code – open the full COMPSCI220 study guide
Full guide + ask Sia
about COMPSCI220
SIDE 2/2   5 WORKED DRILLS · IF X → DO Y · TRAPS · FAST RECALL Exam revision sheet S2 2026 · answer before revealing the path

7 · Drill 1 — Big-O ProofC1 · 5-mark method

Prompt: Use the Big-O definition while deriving an asymptotic bound from an operation count. Define quantities, transform, check and qualify.

1 T,n,g2 c,n₀3 n≥n₀4 upper
Answer ladder: definition → constants → inequality → qualified conclusion.
  1. Write T(n) ∈ O(g(n)) and define the input variable and counted work.
  2. Exhibit positive c,n₀; show 0 ≤ T(n) ≤ c·g(n) for every n ≥ n₀.
  3. Check the claimed inequality or a limiting case independently.
  4. Conclude only an eventual upper bound. Do not claim equality or tightness without evidence.

Answer lineTherefore T(n) ∈ O(g(n)) for the displayed c,n₀; this establishes an eventual upper bound, not necessarily the tightest class.

Mark-bearing moveSelf-check
relationship + symbolsis every quantity defined?
substitution / transformationare sign and comparison visible?
constraintdoes the claim stay inside the definition?

Closed-loop self-mark

DefineCover the notes and say what T, n, g, c and n₀ mean.
TransformPoint to the exact inequality that establishes the bound.
CheckTest the stated range n≥n₀, not only a convenient small input.
InterpretSay “eventual upper bound”; avoid equality or automatic tightness.

Repair drill: replace “the algorithm is efficient” with the counted operation, input variable, inequality and qualified bound.

8 · Drill 2 — Merge CostC2 · 5-mark method

Θ(log n)Θ(n)Θ(n log n)×=check stability + memory
Worked recurrence: height of the recursion × work across each level.

9 · Drill 3 — Heap IndicesC3 · 5-mark method

Prompt: Explain zero-based child lookup while executing a heap operation.

left(i)=2i+1 · right(i)=2i+2

iL: 2i+1R: 2i+2exists iff index < length
Formula gives candidate positions; a bounds check determines existence.
  1. Name zero-based representation.
  2. Substitute the current index i into both formulas.
  3. Compare each candidate with array length.
  4. Use only existing children in the ordering comparison.
  5. Trace each move until the heap relation is restored; relate moves to height.
ClaimAllowed only when
child existscandidate index < length
operation follows a short paththe complete-tree height controls moves
BST operation is logarithmicBST height remains logarithmic

Heap trace ledger

StepWrite beside the array/tree
Locatecurrent index, candidate child indices, array length
Validatewhich candidates are inside the array
Comparethe parent–child ordering test actually used
Moveentries and indices before/after the change
Stopthe restored heap relation
Costnumber of moves as a path through tree height

BST contrast: use key comparisons and links; the path length is the actual height. If insertion order degenerates the tree, qualify the cost.

Trap A formula can point outside the stored array. Computing an index does not create a node.

10 · Hashing Quick TestC4 · changed scenario

Before looking back, write: α = ____ / ____. Then name three dependencies behind an expected constant-lookup claim.

α = n/mtrace ruleE[T] costnot worst-case O(1)
Hash response: occupancy calculation, collision trace, conditional performance claim.

11 · Drill 4 — BFS DiscoveryC5 · 5-mark method

Prompt: Trace a traversal, record discovery structure and identify reachable components.

On first discovery of v from u:
d(v)=d(u)+1 · pred(v)=u · enqueue v once

s:0u:1x:1v:2y:2queue order: nondecreasing distanceadjacency order may change predecessor
BFS drill: label distance and predecessor at first discovery, not at later encounters.
  1. State the representation and start vertex.
  2. Initialise start distance, then process neighbours in the given adjacency order.
  3. On first discovery only, set distance/predecessor and enqueue once.
  4. The discovered set gives the reachable component under the graph’s direction rules.
  5. Qualify: the stored tree/order may vary with adjacency order; shortest unweighted edge counts do not.
If the prompt says…Record…
trace BFSqueue, discovery order, distance, predecessor
componentmaximal reachable set under direction rules
shortest route with weightsdo not reuse the unweighted BFS distance rule

Five-column trace you can self-mark

DequeuedAdjacency examinedNewly discoveredDistancePredecessor
current vertexgiven orderfirst encounters onlyparent + 1discovering vertex
next queuedcontinue in ordernever enqueue twiceunchanged laterunchanged later

Completion test: when the queue is empty, the discovered set is exactly what the traversal reached from the start under the direction rules. To identify all components, the same traversal logic must restart from an undiscovered vertex until none remain.

Order qualification: if adjacency order changes, write the new queue and predecessor choices; do not change the shortest unweighted distances. This distinction is the quickest check on whether a trace confuses representation order with graph distance.

Fast-recall terms

Representationstructure recording vertices and edges, such as adjacency lists or a matrix
BFSvisits vertices in nondecreasing unweighted distance
Componentmaximal mutually reachable set under direction rules
Discovery treestored predecessor structure; may vary with adjacency order

12 · Drill 5 — Relaxationcourse worked example · 4 marks

Given: d(u)=7, d(v)=12, and w(u,v)=3. Apply one relaxation and explain the condition.

ud=7w=3v12 → 10candidate 7+3=10 < 12therefore update
The guide’s worked values carried through: candidate, comparison, update, qualification.
  1. 1: candidate through u = 7+3=10.
  2. 1: compare candidate 10 with current 12.
  3. 1: set d(v)=10 and predecessor of v to u because the candidate is smaller.
  4. 1: a non-improving candidate changes neither record; algorithm assumptions on edge weights still matter.

Full conclusionRelaxation changes d(v) from 12 to 10 and records u. This is a tentative improvement; the step alone does not prove 10 globally final.

Shortest-path tree or MST?

QuestionTargetDo not claim
cheapest route from sourceshortest-path distances/treeminimum total connecting tree
connect all vertices cheaplyMST of connected undirected graphevery pairwise path is shortest
candidateimproves?updatetentative dalgorithmpermits final?local relaxation ≠ global finality
Finality is supplied by the surrounding algorithm, not by the relaxation inequality alone.

Relaxation decision card

ComparisonDistancePredecessorClaim
d(u)+w(u,v) < d(v)replace with candidateset to utentative improvement
d(u)+w(u,v) is not smallerunchangedunchangedno improvement through this edge

Before executing the arithmetic, define whether the graph is directed or undirected as the representation requires and identify the edge being examined. After the arithmetic, keep the local update separate from the algorithm’s later proof of finality.

Objective check: shortest-path work accumulates edge weights along routes from a source. MST work selects an acyclic connecting set of minimum total weight in a connected undirected graph. Similar-looking trees do not make the objectives equivalent.

13 · Method Chooserall chapters · if X → Y

If you see…Do thisMust qualify
growth / scalingcount operations; name n; prove a bound with c,n₀upper bound may not be tight
why loop worksstate invariant; trace state before/after iterationtests are not proof
divide-and-conquer costidentify subcalls + combine work + levelsworst case, memory, stability
heap indexuse 2i+1, 2i+2; bounds-checkcandidate ≠ existing child
BST operationtrace comparisons down the actual treecost follows height
hash collisionshow computed slot and complete resolution pathexpected cost assumptions
unweighted reachabilityBFS queue + first-discovery distance/predadjacency-order effect
weighted distancerelax only an improving candidateedge-weight / algorithm conditions
connect all vertices cheaplyidentify MST objectiveconnected, undirected; not all-pairs paths
objective?reach?weightedspan allBFSshortest pathMST
Judgement card: read the objective before selecting a graph method.

Universal trace frame

Use for every algorithm responseINPUT / representation → STATE before → operation + condition → STATE after → invariant / objective → cost from counted work → assumption / limit

This frame separates what changed from why the change is valid and from how much work it costs. When stuck, write the current state and the condition controlling the next legal move.

Output anatomy — turn working into a conclusion

Sentence jobRequired content
Defineprecise course term and represented object
Selectwhy this method matches the requested objective

14 · Classic TrapsFAQ limits · self-mark

Tempting answerWhy it failsRepair sentence
“It passed the examples, so it is correct.”examples are not proofgive the invariant and state transition
“O(g) means equal to g.”Big-O is an eventual upper boundexhibit c,n₀; avoid equality/tightness claim
“Merge contributes a third recursive call.”merge is additive linear work2T(n/2)+cn
“Every BST operation is logarithmic.”insertion order may degenerate heightcondition the cost on actual height
“2i+1 is always a child.”index may be out of boundscheck against array length
“α counts occupied buckets.”wrong numerator/denominatorstored entries / capacity
“Hash lookup is always constant.”expected claim needs assumptionsname hash, collision and resizing conditions
correct?invariantexists?boundsfinal?algorithmfast?limitsqualify the conclusion,not just the calculation
Four recurring checks: proof, existence, finality and performance assumptions.

Fast-recall terms

Invarianttrue before and after each iteration; supports correctness
Stabilityequal-key records retain relative order
Tree heightmaximum edge count on a downward root-to-leaf path
Componentmaximal mutually reachable set under direction rules
Shortest pathminimum allowed path weight under method assumptions
MSTminimum-total-weight acyclic connector of all vertices

15 · Exam-Morning Planbrief · final review

retrieveformulastrace onenew casesay eachboundaryLMSrulesrecall → apply → qualify→ verify operations
Final review control: retrieval and changed-case practice, then operational verification.
    https://www.asksia.ai/cheatsheet/auckland-compsci220 · Full COMPSCI220 study guide →
    Forward this to your tutorial group · Shared by ________
    AskSiav2 · 2026-10-25
    Semester Two examination period, 29 October – 16 November 2026 (check your personal exam timetable).
    Check your exam instructions on the LMS for what you may bring; use this sheet to revise and self-test.

    Want one for YOUR exact syllabus?

    Sia is your free desktop study agent. Drop your University of Auckland COMPSCI220 slides — Sia builds a sheet tailored to YOUR exam. Better than this library because it knows YOUR materials.

    ↓ Download Sia · Free