Algoistan

Cheat sheets

Dart, Big-O and interview patterns on one printable page. Every row is copied from a lesson's own cheat sheet or tables, and the step badge on the right takes you to the section it came from, where the animation and the tested Dart explain it from zero.

252 rows in 8 sections. Wide tables scroll sideways on a phone.

1. Big-O at a glance

What each growth class means, how big an input it can handle, and the notation rules the course uses.

Growth classes, slowest-growing first

ClassWhat it meansLargest n in 1 second (10⁸ operations)Example in the courseFrom
O(1)The work does not grow at all.unlimited: the cost never depends on nList a[i] read: base + index × slot size, one loadStep 13.1 Step 4.1 Step 3.1
O(lg n)Halve the candidates each step; the base of the log is only a constant factor.effectively unlimited (n = 2^(100,000,000))Binary searchStep 4.1 Step 4.1 · cheat sheet Step 13.5 Step 5.1
O(√n)Between lg n and n in the growth order.10¹⁶Compact sorted list + random jumps: O(√n) expected searchStep 4.1 Step 4.1 · cheat sheet Step 7.1
O(n)Twice the input, about twice the work.100,000,000Linear searchStep 13.1 Step 4.1 Step 5.1
O(n lg n)n work per level × (lg n + 1) levels.4,523,071Merge sort, heapsortStep 4.1 Step 4.1 · cheat sheet Step 5.2 Step 6.1
O(n²)Twice the input gives four times the work.10,000Insertion sort (average and worst case)Step 13.1 Step 4.1 Step 5.2
O(n³)Doubling n multiplies n³ by 8.464Floyd-Warshall, naive matrix multiplyStep 4.1 Step 10.4 Step 5.4
O(2ⁿ)Doubling the computer's speed only adds 1 to the largest solvable n.26Try every subsetStep 4.1 Step 13.1
O(n!)n tasks have n! orderings.11Try every permutationStep 4.1 Step 5.1

Read the constraints: they tell you the speed you need

Largest nFits in about 1 sToo slowFrom
n ≤ 20O(2ⁿ): try every subsetO(n!) once n passes about 11Step 13.1
n ≤ 3 000O(n²) = 9·10⁶O(n³) = 2.7·10¹⁰Step 13.1
n ≤ 10⁵ to 10⁶O(n log n) or O(n)O(n²) = 10¹⁰ or moreStep 13.1
n ≤ 10⁸O(n) with a tiny constantO(n log n) starts to hurtStep 13.1

The five notations

NotationMeaningLikeFrom
O(g)Upper bound (a ceiling): f ≤ c·g for n ≥ n₀≤Step 5.3 Step 4.1
Ω(g)Lower bound (a floor): f ≥ c·g for n ≥ n₀≥Step 5.3 Step 4.1
Θ(g)Tight bound, both at once (a sandwich): c₁g ≤ f ≤ c₂g for n ≥ n₀=Step 5.3 Step 4.1
o(g)Strict upper: f/g → 0<Step 5.3
ω(g)Strict lower: f/g → ∞>Step 5.3

Rules worth memorising

RuleStatementFrom
Growth order1, lg n, √n, n, n lg n, n², n³, 2ⁿ, n!Step 4.1
Tight-bound theoremf = Θ(g) ⟺ f = O(g) and f = Ω(g)Step 5.3
PolynomialDegree d with a positive leading coefficient ⟹ Θ(n^d)Step 5.3
Exponential beats polynomialn^b = o(aⁿ) for any constant a > 1Step 5.3
Log beats no positive powerlg^k n = o(n^a) for any constant a > 0Step 5.3
Factorialsn! = o(nⁿ), n! = ω(2ⁿ), lg(n!) = Θ(n lg n)Step 5.3
Arithmetic seriesΣi = n(n+1)/2; Σi² = n(n+1)(2n+1)/6Step 4.1
Geometric seriesΣ xᵏ (k = 0..n) = (xⁿ⁺¹ − 1)/(x − 1); infinite, |x| < 1: 1/(1 − x)Step 4.1
Harmonic seriesHₙ = Σ 1/k ≈ ln n; ln(n+1) ≤ Hₙ ≤ ln n + 1Step 4.1
T(n) = 2T(n/2) + nΘ(n lg n): n work per level × lg n + 1 levelsStep 4.1
T(n) = 8T(n/2) + Θ(n²)Θ(n³) (recursive matrix multiply)Step 5.4
T(n) = 7T(n/2) + Θ(n²)Θ(n^lg 7) ≈ Θ(n^2.807) (Strassen)Step 5.4

2. Dart collections and their costs

The operations interviews use most, with the cost the Level 3 "Every built-in method" lessons measured.

List

OperationTime (why)Watch outFrom
a[i] read / a[i] = vO(1): address = base + index × slot size, after a bounds checkRangeError if index < 0 or ≥ lengthStep 3.1
length, first, lastO(1)first / last throw StateError on an empty listStep 3.1
addO(1) amortised: a rare grow costs O(n) but doubles capacityUnsupportedError on a fixed-length or unmodifiable listStep 3.1
addAllO(k) for k new elementsStep 3.1
insert(i, v)O(n − index): the tail must shift; insert at 0 is O(n)RangeError unless 0 ≤ index ≤ lengthStep 3.1
removeLastO(1): just length--, nothing movesRangeError on an empty VM listStep 3.1
removeAt(i)O(n − index): removing at 0 is the worst caseRangeError if index is out of rangeStep 3.1
remove(v)O(n): linear search, then the tail shifts leftStep 3.1
contains, indexOfO(n): no hash or order to exploitUse a Set for fast membershipStep 3.1
sublist(a, b)O(k), k = b − a: copies k referencesRangeError unless 0 ≤ start ≤ end ≤ lengthStep 3.1
sortO(n log n) average: dual-pivot quicksort above 33 elements, insertion sort for 33 or fewerElements must be comparableStep 3.1
reversed, map, whereLazy view: O(1) to create, O(n) when consumed (again on every pass)map caches nothingStep 3.1
toList, toSetO(n): copies n references / one hash insert per element (expected)Step 3.1

Rule of thumb: default to List. Switch to Set when you keep asking "is it in there?", to ListQueue when you remove from the front, and to a typed list (Uint8List, Float64List) when you hold millions of numbers. Step 3.1

Set (HashSet / LinkedHashSet / SplayTreeSet)

OperationHash setsSplayTreeSetFrom
addO(1) expected + amortised (the table doubles when full)O(log n) amortisedStep 3.2
contains, lookupO(1) expectedO(log n) amortised (splays the found node to the root)Step 3.2
removeO(1) expectedO(log n) amortisedStep 3.2
union(other)O(n + m) expected: copy this set, then add the m elements of otherStep 3.2
intersection(other)O(n) expected: one other.contains per element of this set; call it on the smaller setStep 3.2
difference(other)O(n) expectedStep 3.2
length, isEmptyO(1): a stored counterStep 3.2
elementAt(i)O(index): it iterates and counts; in a loop that is O(n²), so call toList() firstStep 3.2

Map (HashMap / LinkedHashMap / SplayTreeMap)

OperationHash mapsSplayTreeMapFrom
m[k]O(1) expected; a missing key gives null, never an errorO(log n) amortisedStep 3.2
m[k] = vO(1) expected + amortisedO(log n) amortisedStep 3.2
containsKeyO(1) expectedO(log n) amortisedStep 3.2
containsValueO(n): no index over values, a linear scan comparing each with ==Step 3.2
putIfAbsentO(1) expected plus the cost of ifAbsentO(log n) amortisedStep 3.2
updateO(1) expected plus the callbackO(log n) amortisedStep 3.2
removeO(1) expectedO(log n) amortisedStep 3.2
keys, values, entriesO(1) to get, O(n) to walk; adding or removing keys while iterating throws ConcurrentModificationErrorStep 3.2
firstKey, lastKey, lastKeyBefore, firstKeyAfter—O(log n) amortisedStep 3.2

update(k, f) throws ArgumentError ("Key not in map") when the key is missing and ifAbsent is omitted. Step 3.2

Queue, ListQueue and LinkedList (dart:collection)

OperationListQueueDoubleLinkedQueueFrom
addLast / addO(1) amortised: store at tail, double the table when fullO(1)Step 3.3
addFirstO(1) amortised: the head index steps back, wrapping aroundO(1)Step 3.3
removeFirst, removeLastO(1)O(1)Step 3.3
first, last, lengthO(1)O(1)Step 3.3
elementAt(i)O(1): index arithmetic, one readO(index): one link step per positionStep 3.3
remove(value)O(n): both scan from the frontStep 3.3
LinkedList add / remove / containsO(1) each (List.remove would search: O(n))Step 3.3

removeFirst / removeLast on an empty queue throw StateError ("Bad state: No element"). Step 3.3

String and StringBuffer

OperationTime (n = length)NoteFrom
s[i], codeUnitAt(i), lengthO(1)Indexes count UTF-16 code unitsStep 3.5 Step 1.5
substring(a, b)O(k) for a piece of k unitsEnd index excludedStep 3.5 Step 1.5
a + bO(a + b): both operands are copiedA loop of += is Θ(n²)Step 3.5
StringBuffer.writeAmortised O(length of the piece)The existing text is not copiedStep 3.5
StringBuffer.toStringO(n): one allocation, one copyBuild across many steps with a StringBuffer: O(n) vs O(n²)Step 3.5 Step 1.5
indexOf, containsO(n·m) worst caseA simple scan, no clever searchStep 3.5
startsWith, endsWithO(m)Step 3.5
==O(1) if identical or lengths differ, else O(n)Use == for content, never identityStep 3.5 Step 1.5
hashCodeO(n) the first time, then O(1) (cached)Step 3.5
compareToO(min(n, m))By code unit: uppercase < lowercaseStep 3.5 Step 1.5
split, trim, toUpperCaseO(n)Each returns a new StringStep 3.5
runesWalking all runes O(n); Runes.length O(n)Use for emoji-safe length and reverseStep 3.5 Step 1.5

Rules of thumb: a String never changes; indexes count code units; runes counts code points; loops that grow a string use StringBuffer; compile a RegExp once; replaceAll is literal. Step 3.5

int and double

TopicFactFrom
int64-bit two's complement (native); range ±2⁶³; overflow wraps silently; on the web exact only up to 2⁵³Step 1.4
doubleIEEE-754 64-bit; never compare with == after maths; double.nan != double.nanStep 1.4
/ ~/ % remainder/ always gives a double; ~/ truncates; % is Euclidean (always ≥ 0); remainder() takes the sign of the dividendStep 1.4
+ / ~/ %O(1): one CPU instruction or one hardware division; int ~/ 0 and int % 0 throwStep 3.6
& | ^ ~ << >> >>>O(1); >> keeps the sign, >>> fills with zeros; a negative shift throws ArgumentErrorStep 1.4 Step 3.6
Bit tricksn & (n − 1) clears the lowest set bit; power-of-two test: n & (n − 1) == 0; x ^ x == 0Step 1.4
round, floor, ceil, truncateO(1); UnsupportedError for NaN and ±InfinityStep 3.6
int.parse / int.tryParseO(L) for L characters; parse throws FormatException, tryParse returns nullStep 3.6 Step 1.4
gcdO(log min(|a|, |b|)) (Euclid)Step 3.6
modPowO(log exponent) multiplicationsStep 3.6
bitLength, isEvenO(1)Step 3.6
toStringO(digits): at most 20 for an int, 17 significant for a doubleStep 3.6
BigIntArbitrary precision; * is O(n·m) schoolbook; parse is O(L²)Step 3.6 Step 1.4

3. Dart language essentials

Null safety, final vs const, operators, records and patterns, and async from Levels 1 and 2 and the side track.

Null safety

NeedUseNotesFrom
Allow null for a typeT?Non-nullable by default otherwiseStep 1.6
Stop a chain safely on nulla?.b?.cShort-circuits at the first nullStep 1.6
Fallback value when nulla ?? bb only evaluated if a is nullStep 1.6
Fill in a default oncea ??= bNo-op if a is already non-nullStep 1.6
"I promise it is not null"a!Throws TypeError at run time if wrongStep 1.6
Spread a possibly-null list[...?maybeList]Inserts nothing if nullStep 1.6
Narrow after a checkif (x != null) { ... }Flow-analysis promotion; also is checks and early returnStep 1.6
Promote a public fieldCopy to a local, or if (f case final v?)Fields do not promote directly (except private final, 3.2+)Step 1.6
Set later, read as non-nulllate T x;LateInitializationError if read before setStep 1.6
Force a named argument{required T x}Compile error if omittedStep 1.6
Drop nulls from a listxs.nonNullsOr xs.whereType<T>()Step 1.6

var, final, const, late

KeywordWhen fixedContents mutable?Canonicalised?From
varType inferred once at declarationDepends on the objectNoStep 1.3
finalReference set once, at run timeYes, if the object is mutableNoStep 1.3
constValue fixed at compile timeNo: deeply frozenYes: equal literals share one objectStep 1.3
lateDeferred to first read (then cached)n/a (timing, not mutability)NoStep 1.3
dynamicNever checked at compile timen/aNoStep 1.3

Rules of thumb: assignment copies the arrow; final fixes the variable; const fixes the object; a copy constructor is shallow; never mutate what feeds hashCode. Step 2.2

Operators and control flow

TopicKey factFrom
Equality== is value equality (overridable); identical() means the same object in memoryStep 1.7
Logical&& and || short-circuit: the right side may never runStep 1.7
++ / --Postfix returns the OLD value then changes; prefix changes then returns the NEW valueStep 1.7
Cascade.. chains calls on the same receiver; ?.. skips all of them if the receiver is nullStep 1.7
is / asis tests and promotes; as casts and can throwStep 1.7
switch (Dart 3)No accidental fall-through; expressions use => and support patterns and when guards; both forms must be exhaustiveStep 1.7
break / continuebreak exits the loop now; continue skips to the next iteration; break outer; exits labelled loopsStep 1.7
assertNo-op unless --enable-asserts (or Flutter debug); stripped from release buildsStep 1.7

Records, patterns and sealed classes (Dart 3)

ConceptSyntax / ruleFrom
Positional record(1, 'a'), fields via $1, $2Step 2.5
Named record(x: 1, y: 2), fields via .x, .yStep 2.5
Record equalityStructural == with a matching hashCode, generated automatically; immutableStep 2.5
Return several values({int min, int max}) minMax(...) { ... return (min: lo, max: hi); }Step 2.5
Declaration / swapvar (a, b) = (1, 2); (a, b) = (b, a);Step 2.5
PatternsList [a, b, ...rest], map {'k': v}, object Point(x: var px), relational >= 0, logical >= 75 && < 90Step 2.5
Null-check / null-assertvar n? fails cleanly on null; var x! throws on nullStep 2.5
if-case with guardif (v case pattern when cond) { ... }Step 2.5
for-in destructuringfor (final (a, b) in pairs) { ... }Step 2.5
Sealed classAll direct subtypes in the same library; enables exhaustiveness checkingStep 2.5
ExhaustivenessMissing a subtype's case is a compile error; a wildcard _ or every case makes it exhaustiveStep 2.5

async, await and the event loop

ConceptRuleFrom
One isolateRuns exactly one thing at a time; async means non-blocking, not simultaneousStep S.1
Event loop orderRun the stack to empty, drain the whole microtask queue, run ONE event, repeatStep S.1
Microtask queuescheduleMicrotask, Future.microtask, the continuation right after an awaitStep S.1
Event queueFuture(fn), Timer, Future.delayed (even Duration.zero), I/OStep S.1
async / awaitRuns synchronously up to the first await, suspends, returns a Future immediatelyStep S.1
Errorstry/catch around await catches a failed Future like a sync throwStep S.1
Sequential vs parallelTwo awaits in a row: times add up. Future.wait([...]): total ≈ the slowest oneStep S.1
StreamsSingle-subscription: one listener ever. Broadcast: many listeners, no replay. Cancel subscriptions when doneStep S.1
Completer<T>Bridges a callback API: complete(value) or completeError(e) exactly onceStep S.1
Pitfalllist.forEach(asyncFn) never awaits anything: use a for loop with awaitStep S.1

4. Sorting, searching and selection

Best, average and worst time, extra space, stability and in-place for every sort in Level 6.

Sorting algorithms

AlgorithmBestAverageWorstSpaceStable?In place?Use whenFrom
Insertion sortΘ(n)Θ(n²)Θ(n²)O(1)YesYesSmall n, or nearly sorted data (Θ(n + D), D = inversions)Step 5.2
Selection sortΘ(n²)Θ(n²)Θ(n²)O(1)NoYesMinimising swaps matters more than comparisonsStep 5.2
Bubble sortΘ(n²) (Θ(n) with an early-exit flag)Θ(n²)Θ(n²)O(1)YesYesTeaching onlyStep 5.2
Merge sortΘ(n lg n)Θ(n lg n)Θ(n lg n)Θ(n)YesNoGuaranteed Θ(n lg n), linked lists, external dataStep 5.2
HeapsortΘ(n lg n)Θ(n lg n)Θ(n lg n)O(1) extraNoYesΘ(n lg n) in every case with distinct keys (all-equal keys: Θ(n))Step 6.1
Quicksort (deterministic)Θ(n lg n)Θ(n lg n)Θ(n²) (sorted input)O(lg n) stack average, O(n) worstNoYesAvoid on data that may already be sortedStep 6.2
Randomised quicksortΘ(n lg n)Θ(n lg n) expected, any inputΘ(n²) (astronomically unlikely)O(lg n) expected stackNoYesDefault general-purpose in-place sortStep 6.2
Three-way quicksortΘ(n) (all equal)Θ(n lg n)Θ(n²)O(1) extraNoYesMany duplicate keysStep 6.2
Counting sortΘ(n + k)Θ(n + k)YesNoSmall integer range k = O(n)Step 6.3
Radix sortΘ(d(n + k))Θ(n + k)YesNoFixed-width integers or stringsStep 6.3
Bucket sort—Θ(n)Θ(n²)Θ(n)Not guaranteedNoRoughly uniform real values in a known rangeStep 6.3
Dart List.sort—O(n log n)———Yes (mutates the list)Dual-pivot quicksort above 33 elements; insertion sort (O(n²) worst case, fast for tiny lists) for 33 or fewerStep 3.1

Any comparison sort is Ω(n lg n) in the worst case: a hard floor. Counting, radix and bucket sort get below it by assuming something about the values (a small range, a fixed width, a uniform spread). Step 6.3

Searching and selection

AlgorithmBestAverageWorstSpaceNeedsFrom
Linear searchΘ(1)Θ(n)Θ(n)Θ(1)Nothing: unsorted data is fineStep 5.1
Binary searchΘ(1)Θ(lg n)Θ(lg n)Θ(1) iterative, Θ(lg n) recursiveSorted dataStep 5.1
Minimumn − 1 comparisons, provably optimalO(1)NothingStep 6.4
Minimum and maximum together≤ 3⌊n/2⌋ comparisons by pairing (naive 2n − 2)O(1)NothingStep 6.4
randomizedSelect (i-th smallest)—Θ(n) expectedΘ(n²)—Recurses into only one side after partitionStep 6.4
SELECT (median of medians)——Θ(n) guaranteed—Groups of 5Step 6.4

5. Data structures: operations and costs

Stacks, heaps, hash tables, search trees, union-find and amortised structures from Levels 7 to 9.

Stacks, queues and linked lists

StructureSearchInsertDeleteUse whenFrom
Array stack—O(1) pushO(1) popLIFO: undo history, DFS, bracket checksStep 7.1
Circular-array queue—O(1) enqueueO(1) dequeueFIFO: scheduling, BFS, buffersStep 7.1
Doubly linked list (sentinel)Θ(n)O(1) at a known nodeO(1) at a known nodeMid-list splicing; an LRU cache's recency orderStep 7.1

Heaps and priority queues

OperationBinary heapFibonacci heap (amortised)From
Build from n itemsΘ(n) (buildMaxHeap)—Step 6.1
InsertO(lg n)O(1)Step 6.1 Step 9.2
Peek max / minΘ(1)O(1)Step 6.1 Step 9.2
Extract max / minO(lg n)O(lg n) (O(n) worst single call)Step 6.1 Step 9.2
Increase / decrease keyO(lg n)O(1)Step 6.1 Step 9.2
Union—O(1)Step 9.2
Delete—O(lg n)Step 9.2
Parent / children of index i(i - 1) ~/ 2, 2 * i + 1, 2 * i + 2: O(1)—Step 13.8

A d-ary heap: insert O(log_d n), extract O(d · log_d n). A Fibonacci heap pays off when an algorithm makes many decreaseKey calls per extractMin on a dense graph (Dijkstra, Prim). Step 6.1 Step 9.2

Hash tables

MethodSearch (average)Search (worst)SpaceUse whenFrom
ChainingΘ(1 + α)Θ(n)Θ(n + m)Default choice; simplest deletion; α can exceed 1Step 7.2
Chaining + universal hashingO(1 + α) expected, any inputΘ(n)Θ(n + m)Keys might be adversarialStep 7.2
Linear probing≤ 1/(1 − α)Θ(n)Θ(m), α ≤ 1Cache-friendly, but primary clustering at high αStep 7.2
Double hashing≈ 1/(1 − α)Θ(n)Θ(m), α ≤ 1Closest to ideal uniform hashing; needs gcd(m, h₂(k)) = 1Step 7.2
Perfect hashing (two-level)Θ(1)Θ(1)O(n) expectedStatic key sets needing a worst-case guaranteeStep 7.2

Search trees

StructureSearch / insert / deleteHeightNotesFrom
Binary search treeO(lg n) average (random BST), O(n) worst (a chain)O(lg n) expected if randomly builtNo rebalancing; degrades on sorted inputStep 7.3 Step 7.4
Red-black treeO(lg n)≤ 2 lg(n + 1)Insert ≤ 2 rotations, delete ≤ 3Step 7.4
AVL treeO(lg n)≤ 1.44 lg(n + 2)O(1) rotations per insertStep 7.4
TreapO(lg n) expectedΘ(lg n) expected< 2 expected rotations per insertStep 7.4
Order-statistic treeselect(i) and rank O(lg n) balanced—Each node stores its subtree sizeStep 7.5
Interval treeintervalSearch O(lg n) balanced—Keyed by low endpoint; node stores max highStep 7.5
B-tree (minimum degree t)O(log_t n) disk accesses; O(t · log_t n) CPUh ≤ log_t((n + 1)/2)Root split is the only way height growsStep 9.1
van Emde Boas treeO(lg lg u) for every operation—Θ(u) space; min and max O(1)Step 9.3

Disjoint sets (union-find)

RepresentationfindSetunionm operationsFrom
Linked list + weighted unionΘ(1)Θ(shorter list) relabellingO(m + n lg n)Step 9.4
Forest, union by rank onlyO(lg n)O(lg n)O(m lg n)Step 9.4
Forest, union by rank + path compressionO(α(n)) amortisedO(α(n)) amortisedO(m·α(n)): linear in practice (α(n) ≤ 4)Step 9.4

Amortised costs and tries

Structure / operationCostWhyFrom
Stack push / pop / multipopAmortised O(1) per operationPotential = stack sizeStep 8.3
Binary counter incrementAmortised O(1) from 0Potential = number of 1-bitsStep 8.3
Dynamic table insert (doubling)Amortised ≤ 3 per insertLoad factor stays ≥ 1/2Step 8.3
Trie insert / search / startsWithO(L) per callOne letter per step; space O(total letters)Step 13.8

6. Graph algorithms

Search, minimum spanning trees and shortest paths from Level 10: time, space and when to use each.

AlgorithmTimeSpaceNeedsUse it forFrom
BFSO(V + E)O(V)Any graphFewest-edges distance and shortest-path tree from a sourceStep 10.1
DFSΘ(V + E)O(V)Any graphDiscovery/finish times, edge classes; a back edge means a cycleStep 10.1
Topological sortΘ(V + E)O(V)A DAGAn order respecting every "must come before" edgeStep 10.1
Strongly connected componentsΘ(V + E)O(V + E)A directed graphEvery maximal mutually reachable groupStep 10.1
Kruskal (MST)O(E lg V) (the sort dominates)O(V + E)Disjoint-set forestSparse graphs, edge list givenStep 10.2
Prim, arrayO(V²)O(V)Array scanDense graphs (E ≈ V²)Step 10.2
Prim, binary heapO((V + E) lg V)O(V + E)Binary min-heapGeneral purpose, sparse graphsStep 10.2
Prim, Fibonacci heapO(E + V lg V) amortisedO(V + E)Fibonacci heapVery dense graphs, in theoryStep 10.2
Bellman-FordO(VE) worst (Θ(V + E) with early stop once converged)O(V)Negative edges allowedDetects a negative cycle (returns false)Step 10.3
DAG shortest pathsΘ(V + E)O(V)An acyclic graph; negative edges fineScheduling, critical path, longest path by negationStep 10.3
Dijkstra, arrayΘ(V²)O(V)Non-negative weightsDense graphsStep 10.3
Dijkstra, binary heapO((V + E) lg V)O(V)Non-negative weightsSparse graphsStep 10.3
Dijkstra, Fibonacci heapO(V lg V + E) amortisedO(V)Non-negative weightsVery large sparse graphsStep 10.3
Floyd-WarshallΘ(n³)Θ(n²)Negative weights fine, no negative cycleAll pairs on dense graphs; negative diagonal = negative cycleStep 10.4
JohnsonO(V² lg V + VE) (Fibonacci heap)O(V²) outputNegative edges fineAll pairs on sparse graphsStep 10.4
Transitive closureΘ(n³)Θ(n²) bitsReachability only"Can i reach j at all?"Step 10.4

Dijkstra with a negative edge gives silently wrong answers: it terminates but returns wrong values. Use Bellman-Ford, or Johnson's reweighting. Step 10.3 Step 10.4

7. Interview patterns

Level 13 in one table: the words that give a pattern away, the shape of its solution, and the problems solved on each page.

PatternSignal in the questionTemplate ideaTypical problemsFrom
Arrays & hashingThe inner loop keeps asking the same question; positions matter and the list is unsortedTrade memory for time: keep answers in a Set or Map, e.g. look up target − x before storing xTwo Sum, Contains Duplicate, Valid Anagram, Group Anagrams, Top K Frequent, Product Except Self, Longest ConsecutiveStep 13.1 Step 13.1 · intro Step 13.2
Two pointersSorted input (or sorting is affordable) and a rule tells you which end is uselessOpposite ends moving inward; or slow + fast in the same directionValid Palindrome, Two Sum II, 3Sum, Container With Most Water, Trapping Rain Water, Remove DuplicatesStep 13.2
Sliding window"every k in a row", "longest piece with at most …", "shortest piece containing …", "how many pieces have at most …"Grow right; while broken, shrink left; record. Needs a contiguous pieceBuy and Sell Stock, Longest Substring Without Repeats, Character Replacement, Permutation in String, Minimum Window, Window MaximumStep 13.3
Stack"next warmer / bigger / taller", nesting like decode 3[a2[c]], O(1) amortised designMonotonic stack: while the top is smaller than a[i], pop and answer it; push iValid Parentheses, Min Stack, Evaluate RPN, Daily Temperatures, Car Fleet, Largest RectangleStep 13.4
Binary search"is it here, and where?", "first ≥ x", "smallest speed / capacity / day that works"mid = lo + (hi − lo) ~/ 2; every branch must shrink the range; needs sorted data or a test that flips onceBinary Search, 2D Matrix, Koko Eating Bananas, Rotated Minimum, Rotated Search, Median of Two ListsStep 13.5
Linked listsThe head may change; the middle or a cycle; n-th from the endDummy head, fast/slow, a gap of n, save next then reverse the arrowReverse, Merge Two Lists, Cycle, Remove Nth From End, Reorder, LRU Cache, Merge K ListsStep 13.6
TreesSize, height, sum (flows up); depth, path sums, BST windows (flows down); levels, right viewReturn up (postorder), pass down, or BFS by levels; start with the null caseInvert, Max Depth, Diameter, Level Order, Validate BST, Kth Smallest, LCA, SerializeStep 13.7
Tries & heapsPrefix questions ("does any word start with ca?"); k largest of a stream; a running medianTrie of children maps + isEnd; size-k min-heap: push, pop if size > k; two heaps for the medianImplement Trie, Wildcard Search, Kth Largest, Last Stone, K Closest, Task Scheduler, Median StreamStep 13.8 Step 13.8 · intro
GraphsFewest steps; "a before b" orders; merging groups; cheapest path with positive weights; any gridBFS (mark when pushed), DFS, Kahn's in-degree queue, union-find, Dijkstra with a heapIslands, Clone Graph, Rotting Oranges, Course Schedule, Valid Tree, Word Ladder, Network DelayStep 13.9
Intervals & greedy"how many at once", rooms; keep the most / remove the fewest; mergingSort by start and compare with the last block; sort by end and keep if start ≥ last end; sweep lineMerge, Insert, Non-overlapping, Meeting Rooms, Max Subarray, Jump Game, Gas Station, Hand of StraightsStep 13.10
Dynamic programming"how many ways…", "fewest", "cheapest", "longest", "can you…" with overlapping choicesDefine the state in words, build the recurrence from the last move, fill the table; loop direction decides reuseClimbing Stairs, House Robber, Coin Change, LIS, Word Break, LCS, Edit Distance, Partition Equal Subset SumStep 13.11 Step 13.11 · intro
BacktrackingList every arrangement that obeys a ruleChoose, explore, un-choose; record [...path]; start index when order does not matter, used flags when it doesSubsets, Combination Sum, Permutations, Word Search, Palindrome Partitioning, Letter Combinations, N-QueensStep 13.12 Step 13.12 · intro

8. Flutter interview quick facts

The facts Flutter interviews probe most, from the Level 12 cheat sheets.

Widgets, elements and render objects

ConceptFactFrom
WidgetImmutable, cheap description; == is identity; never on screen by itselfStep 12.1
const widgetThe same const expression returns the same object, so Flutter skips it on rebuildStep 12.1
ElementLive instance at a tree position; holds State; BuildContext is the elementStep 12.1
Widget.canUpdateSame runtimeType AND same key: keep the element and update(); else unmount and create newStep 12.1
No keysChildren matched by position: State stays at the position (the reorder bug)Step 12.1
GlobalKeyUnique app-wide; reparenting within one frame keeps State. Create once, never in buildStep 12.1
LifecyclecreateState → initState → didChangeDependencies → build → (didUpdateWidget / setState → build)* → deactivate → disposeStep 12.1
Async gapAfter await: if (!mounted) return; or if (!context.mounted) return;Step 12.1

State management

ConceptFactFrom
Ephemeral vs app stateOne widget cares: State + setState. Shared or must survive: a model object aboveStep 12.2
setState(fn)Run fn now, mark dirty, one rebuild next frame; const children are skippedStep 12.2
InheritedWidgetdependOn… is a one-step lookup plus a dependency; updateShouldNotify true rebuilds dependentsStep 12.2
ValueNotifierNotifies only when the new value is not == the old oneStep 12.2
BuildersValueListenableBuilder / ListenableBuilder rebuild only the builder; the child is built onceStep 12.2
Provider / Riverpod / BlocInherited + ChangeNotifier made easy / providers outside the tree / events → statesStep 12.2

Layout and rendering

ConceptFactFrom
The ruleConstraints go down, sizes go up, the parent sets the positionStep 12.3
BoxConstraintsTight: min = max. Loose: min = 0. Unbounded: max = infinityStep 12.3
Expanded / Flexibleshare = max(0, width − used) ÷ total flex; Expanded = flex × share exactly; Flexible = up to itStep 12.3
ListView in ColumnExpanded (usual), SizedBox, shrinkWrap (lays out every item), or sliversStep 12.3
Framevsync → animate → build → layout → paint → composite → raster; 16.7 ms at 60 fpsStep 12.3
RepaintBoundaryOwn layer; isolates frequent repaints; each layer costs memoryStep 12.3

Async, isolates and platform channels

ConceptFactFrom
Main isolateRuns your Dart UI code plus build, layout and paint; one thing at a timeStep 12.4
async / awaitSame isolate, later: fine for waiting, useless for CPU workStep 12.4
FutureBuilderCreate the Future once (initState, late final or from outside)Step 12.4
Isolate.run / computeOne-shot background isolate; input copied in; errors re-thrown; compute on web = same threadStep 12.4
ChannelsMethodChannel (calls both ways), EventChannel (native → Dart stream), BasicMessageChannel; all asyncStep 12.4
Channel errorsPlatformException = native failed; MissingPluginException = nobody answeredStep 12.4

Performance and testing

ConceptFactFrom
Build modesDebug: JIT, hot reload, slow. Profile: AOT + tracing, real device. Release: AOT, what users getStep 12.5
Rebuild controlconst → split widgets / push state down → builders; helper methods do not stop rebuildsStep 12.5
ListsListView.builder creates only visible + cache items; ListView(children:) creates all up frontStep 12.5
ImagesDecoded ≈ width × height × 4 bytes; set cacheWidth = shown width × device pixel ratioStep 12.5
Pumpingpump() one frame; pump(d) moves fake time; pumpAndSettle times out on endless animationsStep 12.5
Golden testsmatchesGoldenFile; --update-goldens; one consistent machineStep 12.5

Navigation, architecture and release

ConceptFactFrom
NavigatorA stack of routes; the top one is visible, the ones below stay built offstageStep 12.6
Resultsawait Navigator.push<T>(...) gets the value from pop(context, value); null on backStep 12.6
PopScopecanPop: false blocks back gestures and maybePop, but not Navigator.pop; WillPopScope is deprecatedStep 12.6
ArchitectureView → view model → repository → service; constructor injection; fakes in testsStep 12.6
SecretsEverything shipped is readable (strings, defines, assets); secrets stay on your serverStep 12.6
Obfuscation--obfuscate --split-debug-info=dir renames identifiers (not strings); keep the symbolsStep 12.6