Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 143: Knowledge Aids and Quick Reference

Last-Minute Revision Guide


143.1 What Is a Knowledge Aid?

A knowledge aid is a condensed, high-signal reference designed for rapid recall during interviews, contests, or revision. Unlike tutorials that teach from scratch, knowledge aids assume familiarity and focus on pattern recognition, decision shortcuts, and common pitfalls.

Motivation: In a 45-minute interview, you have ~2 minutes to identify the right technique. A mental decision tree turns that from guesswork into systematic elimination.


143.2 Algorithm Decision Tree

When you see a problem, run through this tree to narrow your approach:

Is input sorted or can you sort it?
├─ Yes → Binary Search, Two Pointers, Merge-based
└─ No
   ├─ Need contiguous subarray? → Sliding Window, Prefix Sum, Kadane's
   ├─ Need subsequence (not contiguous)? → DP
   ├─ Graph structure? → BFS / DFS / Dijkstra / Union-Find
   ├─ Tree structure? → DFS / DP on trees / LCA
   ├─ Optimization (min/max)? → DP / Greedy / Binary Search on Answer
   ├─ Counting? → DP / Combinatorics / Inclusion-Exclusion
   ├─ n ≤ 20 (small)? → Bitmask DP / Backtracking / Meet-in-the-Middle
   ├─ n ≤ 1000? → O(n²) DP possible
   └─ n ≤ 10⁶? → O(n log n) required

Decision Flowchart (Text Version)

Clue in ProblemLikely TechniqueTime Complexity
“Sorted array”Binary SearchO(log n)
“Top k” / “k-th smallest”Heap / QuickselectO(n log k) / O(n) avg
“Shortest path” (unweighted)BFSO(V + E)
“Shortest path” (weighted, non-negative)DijkstraO((V+E) log V)
“Shortest path” (negative edges)Bellman-FordO(VE)
“All pairs shortest”Floyd-WarshallO(V³)
“Connected components”DFS / Union-FindO(V + E) / O(α(n))
“Cycle detection”DFS coloring / Floyd’sO(V + E)
“Interval scheduling”Greedy (sort by end)O(n log n)
“Palindrome”Two pointers / DPO(n) / O(n²)
“Serialize tree”BFS / Preorder + markerO(n)
“Random access, fast insert/delete”Hash mapO(1) avg

143.3 STL Quick Reference (C++)

NeedSTL Container / AlgorithmNotes
Sorted containerset, mapO(log n) insert/erase/find
Fast lookupunordered_set, unordered_mapO(1) avg, O(n) worst
Priority queue (max)priority_queue<T>Default is max-heap
Priority queue (min)priority_queue<T, vector<T>, greater<T>>Use greater comparator
Min/Max elementmin_element, max_elementO(n)
Sortsort, stable_sortO(n log n), stable_sort preserves order
Binary searchlower_bound, upper_boundRequires sorted range
Next permutationnext_permutationReturns false at last permutation
Accumulateaccumulate(begin, end, init)Use 0LL for long long
Unique elementsuniqueMust sort first; returns new end iterator
ReversereverseO(n)
RotaterotateO(n)
Partial sortpartial_sort, nth_elementnth_element is O(n)
Countcount, count_ifO(n)
Findfind, find_ifO(n)
Remove (erase-remove)remove + eraseDon’t use erase alone on value

Python Equivalents

NeedPythonNotes
Sorted containersortedcontainers.SortedListpip install sortedcontainers
Fast lookupset(), dict()O(1) avg
Priority queueheapq (min-heap)Use negative values for max
Sortsorted(), .sort()sorted returns new list
Binary searchbisect_left, bisect_rightFrom bisect module
Default dictcollections.defaultdictAuto-initializes missing keys
Countercollections.CounterCounts occurrences
Dequecollections.dequeO(1) append/pop from both ends

143.4 Common Mistakes and Fixes

CategoryMistakeFix
OverflowUsing int for large productsUse long long (C++) or Python’s arbitrary ints
Off-by-onefor (i=0; i<=n; i++) when i<n was intendedCheck loop bounds with small examples
UninitializedUsing uninitialized variablesInitialize everything; use {} or = 0
Iterator invalidationErasing from container while iteratingUse erase-remove idiom or reverse iteration
Signed/unsignedComparing int with size_tCast explicitly or use consistent types
Missing base caseDP without n=0 or n=1 caseAlways write base cases first
Wrong comparisonSort with unstable comparatorEnsure strict weak ordering
Stack overflowDeep recursion (n > 10⁴)Convert to iterative or increase stack size
Modular arithmeticForgetting to mod after multiplicationMod at every intermediate step
Floating pointComparing doubles with ==Use abs(a-b) < epsilon
Graph indexing0-indexed vs 1-indexed confusionClarify at start, adjust accordingly
String indexingOff-by-one in substrings[i:j] in Python is [i, j)

143.5 Complexity Cheat Sheet

Time Complexity Classes

BoundTypical AlgorithmsMax n
O(1)Hash lookup, stack push/popAny
O(log n)Binary search, segment tree10¹⁸
O(√n)Trial division, sqrt decomposition10¹²
O(n)Linear scan, BFS, Union-Find10⁷
O(n log n)Merge sort, Dijkstra, segment tree build10⁶
O(n²)Floyd-Warshall, simple DP5000
O(n³)Matrix chain, Floyd-Warshall500
O(2ⁿ)Subset enumeration20-25
O(n!)Permutation enumeration10-11

Space Complexity Notes

  • Python lists: ~28 bytes per element overhead
  • C++ vectors: ~4 bytes per int, ~8 bytes per pointer
  • For n = 10⁶: ~4 MB for int array, ~8 MB for long long array
  • 2D DP: n×m table uses O(n×m) space; often reducible to O(m) with rolling array

143.6 Pattern Recognition Templates

Two Pointers

// Sorted array: find pair with target sum
int left = 0, right = n - 1;
while (left < right) {
    int sum = arr[left] + arr[right];
    if (sum == target) { /* found */ break; }
    else if (sum < target) left++;
    else right--;
}
# Sorted array: find pair with target sum
left, right = 0, len(arr) - 1
while left < right:
    s = arr[left] + arr[right]
    if s == target:
        break  # found
    elif s < target:
        left += 1
    else:
        right -= 1
// Sorted array: find pair with target sum
int left = 0, right = arr.length - 1;
while (left < right) {
    int sum = arr[left] + arr[right];
    if (sum == target) { break; } // found
    else if (sum < target) left++;
    else right--;
}

Sliding Window

// Longest subarray with sum <= k
int left = 0, sum = 0, maxLen = 0;
for (int right = 0; right < n; right++) {
    sum += arr[right];
    while (sum > k) sum -= arr[left++];
    maxLen = max(maxLen, right - left + 1);
}
# Longest subarray with sum <= k
left = s = max_len = 0
for right in range(len(arr)):
    s += arr[right]
    while s > k:
        s -= arr[left]
        left += 1
    max_len = max(max_len, right - left + 1)
// Longest subarray with sum <= k
int left = 0, sum = 0, maxLen = 0;
for (int right = 0; right < n; right++) {
    sum += arr[right];
    while (sum > k) sum -= arr[left++];
    maxLen = Math.max(maxLen, right - left + 1);
}

Binary Search on Answer

// Minimum value that satisfies condition
int lo = minPossible, hi = maxPossible;
while (lo < hi) {
    int mid = lo + (hi - lo) / 2;
    if (condition(mid)) hi = mid;    // mid works, try smaller
    else lo = mid + 1;               // mid too small
}
// lo is the answer
# Minimum value that satisfies condition
lo, hi = min_possible, max_possible
while lo < hi:
    mid = (lo + hi) // 2
    if condition(mid):
        hi = mid       # mid works, try smaller
    else:
        lo = mid + 1   # mid too small
# lo is the answer
// Minimum value that satisfies condition
int lo = minPossible, hi = maxPossible;
while (lo < hi) {
    int mid = lo + (hi - lo) / 2;
    if (condition(mid)) hi = mid;
    else lo = mid + 1;
}
// lo is the answer

143.7 Interview Checklist

□ Clarify problem (2 min)
   - Input format, constraints, edge cases
   - Ask about duplicates, negatives, empty input
□ Work examples by hand (2 min)
   - At least 2 examples: normal + edge case
   - Trace through your intended approach
□ State approach + complexity (2 min)
   - "I'll use X because Y, time O(?), space O(?)"
   - Mention alternatives and why you chose this one
□ Code cleanly (10 min)
   - Meaningful variable names
   - Handle edge cases inline
   - Don't premature-optimize
□ Trace through example (2 min)
   - Walk through code with your example
   - Check off-by-one, boundary conditions
□ Test edge cases (2 min)
   - Empty input, single element, all same, sorted reverse
   - Integer overflow for large inputs
□ Discuss optimizations (if time)
   - Can you do better time? Better space?
   - Any preprocessing that helps?

143.8 Contest Quick Tips

TipExplanation
Read all problems firstSpend 5 min reading; start with the easiest
Use fast I/O in C++ios_base::sync_with_stdio(false); cin.tie(NULL);
Python: use sys.stdininput() is slow for large input
Precompute when possibleFactorials, powers, prefix sums
Modular arithmeticAlways mod after multiplication: (a * b) % MOD
Print intermediate resultsDebug by printing state at key points
Don’t overthinkIf stuck 10 min, move to next problem
Template codeHave Union-Find, segment tree, etc. ready

143.9 Language-Specific Gotchas

C++

GotchaDetails
vector<bool>Not a real vector; bit-packed; use vector<char> for speed
map vs unordered_mapmap is O(log n), unordered_map is O(1) avg but can TLE with bad hash
endl vs "\n"endl flushes; use "\n" for speed
Global arraysInitialize to 0 by default; local arrays are garbage
__builtin_popcountGCC built-in for bit counting

Python

GotchaDetails
Recursion limitDefault 1000; use sys.setrecursionlimit(300000)
Integer overflowNo issue; Python has arbitrary precision
List vs dequedeque for O(1) front operations
Dictionary orderingDicts preserve insertion order (Python 3.7+)
range is lazyDoesn’t create a list in Python 3

Java

GotchaDetails
Scanner vs BufferedReaderBufferedReader is much faster
Integer.MAX_VALUEUse for infinity in DP
Arrays.sortUses dual-pivot quicksort for primitives
Autoboxingint vs Integer; prefer primitives in tight loops
StringBuilderUse for string concatenation in loops

143.10 Cross-References

TopicRelated Chapter
Binary SearchChapter 3
Two PointersChapter 5
Sliding WindowChapter 7
Dynamic ProgrammingChapter 20-30
Graph AlgorithmsChapter 40-55
TreesChapter 60-70
Number TheoryChapter 80-85
Segment TreesChapter 90
Interview StrategiesChapter 150

Summary

SectionPurpose
Decision TreeMap problem → technique in <2 min
STL ReferenceQuick lookup for C++/Python APIs
Common MistakesAvoid the top 12 pitfalls
Complexity Cheat SheetKnow your limits
Pattern TemplatesCopy-paste-ready code
Interview ChecklistStructured 20-min approach
Contest TipsMaximize score under time pressure

Key Insight: The best interview performers don’t know more algorithms — they recognize patterns faster. Use this chapter as a mental model to build that recognition.