Docsity

Dsa-for-exam-preperation, Cheat Sheet of Mathematics

Toggle sidebar
bg1
Algorithm Patterns & Data Structures Reference
A practical guide for problem solving and coding interviews.
1. Array Patterns
Sliding Window
• Maintain a window of elements over an array or string to reduce O(n²) to O(n).
• Use when asked for: subarrays, substrings, max/min of contiguous range.
• Fixed window: move both pointers together. Variable window: expand right,
shrink left when invalid.
• Examples: Longest substring without repeating characters, max sum subarray of
size k.
Two Pointers
• Use two indices moving toward each other or in the same direction.
• Classic use: sorted array pair sum, removing duplicates, merging sorted arrays.
• Often combined with sorting as a preprocessing step.
Prefix Sums & Difference Arrays
• Prefix sum: precompute cumulative sums to answer range sum queries in O(1).
• Difference array: apply range updates in O(1), reconstruct in O(n).
• 2D prefix sums extend this to matrices for submatrix sum queries.
2. Searching Patterns
Binary Search
• Classic: search a sorted array in O(log n).
• Binary search on the answer: when asked for min/max satisfying a condition,
binary search the answer space.
• Template trigger: 'find the minimum X such that...' or 'what is the smallest/largest
valid value'.
• Examples: Koko eating bananas, minimum days to ship packages, peak element.
Modified Binary Search
• Rotated sorted arrays: determine which half is sorted, search accordingly.
• Search in 2D matrix: treat as flattened 1D array.
• Finding first/last occurrence: adjust boundaries instead of returning immediately.
pf3
pf4
pf5

Partial preview of the text

Download Dsa-for-exam-preperation and more Cheat Sheet Mathematics in PDF only on Docsity!

Algorithm Patterns & Data Structures Reference

A practical guide for problem solving and coding interviews.

1. Array Patterns

Sliding Window

  • Maintain a window of elements over an array or string to reduce O(n²) to O(n).
  • Use when asked for: subarrays, substrings, max/min of contiguous range.
  • Fixed window: move both pointers together. Variable window: expand right, shrink left when invalid.
  • Examples: Longest substring without repeating characters, max sum subarray of size k.

Two Pointers

  • Use two indices moving toward each other or in the same direction.
  • Classic use: sorted array pair sum, removing duplicates, merging sorted arrays.
  • Often combined with sorting as a preprocessing step.

Prefix Sums & Difference Arrays

  • Prefix sum: precompute cumulative sums to answer range sum queries in O(1).
  • Difference array: apply range updates in O(1), reconstruct in O(n).
  • 2D prefix sums extend this to matrices for submatrix sum queries.

2. Searching Patterns

Binary Search

  • Classic: search a sorted array in O(log n).
  • Binary search on the answer: when asked for min/max satisfying a condition, binary search the answer space.
  • Template trigger: 'find the minimum X such that...' or 'what is the smallest/largest valid value'.
  • Examples: Koko eating bananas, minimum days to ship packages, peak element.

Modified Binary Search

  • Rotated sorted arrays: determine which half is sorted, search accordingly.
  • Search in 2D matrix: treat as flattened 1D array.
  • Finding first/last occurrence: adjust boundaries instead of returning immediately.

3. Stack & Queue Patterns

Monotonic Stack

  • Maintain a stack that is always increasing or decreasing.
  • Finds next greater/smaller element for all items in O(n) total.
  • Examples: Daily temperatures, largest rectangle in histogram, trapping rain water.

Monotonic Deque

  • Sliding window maximum/minimum in O(n) using a deque.
  • Front of deque always holds the max (or min) of the current window.

Valid Parentheses / Expression Parsing

  • Use a stack to match opening and closing brackets.
  • Extends to evaluating arithmetic expressions and building abstract syntax trees.

4. Linked List Patterns

Fast & Slow Pointers (Floyd's Cycle Detection)

  • Use two pointers at different speeds to detect cycles in O(n) time and O(1) space.
  • Also finds middle of list, start of cycle, and kth from end.

Reversal & In-place Manipulation

  • Reverse a linked list iteratively or recursively.
  • Reverse a sublist between positions l and r.
  • Examples: Reverse nodes in k-groups, palindrome linked list.

5. Tree Patterns

Tree Traversals

  • Inorder (left-root-right): gives sorted order in BSTs.
  • Preorder (root-left-right): serialization, cloning trees.
  • Postorder (left-right-root): deletion, computing subtree values bottom-up.
  • Level-order (BFS): shortest path, level-by-level processing.

Dijkstra's Algorithm

  • Shortest path in weighted graphs with non-negative edges.
  • Uses a min-heap (priority queue); O((V + E) log V).
  • Generalization: use when you need to process nodes in order of cost.

Bellman-Ford

  • Shortest path allowing negative edges; detects negative cycles.
  • O(VE) — slower than Dijkstra but handles more general cases.

7. Dynamic Programming Patterns

0/1 Knapsack

  • Classic include/exclude decision for each item.
  • dp[i][w] = max value using first i items with capacity w.
  • Variants: subset sum, partition equal subset, target sum.

Unbounded Knapsack

  • Items can be reused unlimited times.
  • Examples: Coin change (min coins), coin change 2 (number of ways), rod cutting.

Longest Common Subsequence (LCS) / Edit Distance

  • 2D DP on two strings or sequences.
  • LCS, longest common substring, edit distance, shortest common supersequence all share the same table structure.

Interval DP

  • Solve problems on subarrays/substrings by merging smaller intervals.
  • Iterate by increasing interval length.
  • Examples: Burst balloons, matrix chain multiplication, palindrome partitioning.

DP on Subsets (Bitmask DP)

  • Enumerate all subsets of a small set (n ≤ 20) using bitmasks.
  • dp[mask] = best result using the subset represented by mask.
  • Examples: Traveling salesman, minimum cost to connect all nodes, assign tasks.

DP on Trees

  • Compute values for each subtree bottom-up via postorder DFS.
  • Examples: Max path sum, house robber on trees, minimum vertex cover.

State Machine DP

  • Model transitions between states (e.g., hold, sold, cooldown).
  • Examples: Best time to buy/sell stock with cooldown or transaction limits.

8. Heap & Priority Queue Patterns

Top K Elements

  • Use a min-heap of size k to find k largest elements in O(n log k).
  • Use a max-heap to find k smallest elements.
  • Examples: Kth largest element, top k frequent words, k closest points.

Two Heaps

  • Maintain a max-heap for the lower half and min-heap for the upper half.
  • Allows O(1) median retrieval, O(log n) insertion.
  • Examples: Find median from data stream, sliding window median.

K-way Merge

  • Merge k sorted lists using a min-heap.
  • Always pop the minimum element and push the next from that list.
  • O(n log k) total where n is total elements.

9. Backtracking

Subsets / Combinations / Permutations

  • Explore all possibilities by building a choice tree recursively.
  • Prune branches early when constraints are violated (bound condition).
  • Track a 'current state' and undo it after each recursive call.
  • Examples: Subsets, combinations sum, permutations, N-queens, word search.

Constraint Satisfaction

  • Backtracking with aggressive pruning for constraint propagation.
  • Examples: Sudoku solver, crossword filling.

10. Greedy Algorithms

Interval Scheduling

  • Sort by end time; greedily select non-overlapping intervals.

13. Advanced Data Structures (Research /

Competitive)

These are primarily academic/research structures. Useful for competitive programming and deep CS knowledge, but rarely tested in standard interviews.

Predecessor Structures

  • Van Emde Boas Trees: O(log log U) query and update, O(n) space with hashing.
  • Fusion Trees: O(log_W n) query time, effective for large word size W.
  • X-fast Tries: O(log log U) query, O(nW) space using hash tables on trie levels.
  • Y-fast Tries: O(log log U) query with O(n) space via indirection and balanced BSTs.

Advanced Sorting

  • vEB/Fusion-based sort: O(n √(log n)).
  • Han-Stock deterministic sort: O(n log log n).
  • Han-Thorup randomized sort: O(n √(log log n)) expected.

Hashing / Dictionary

  • Universal hashing: expected O(1) query time.
  • Dietzfelbinger et al.: worst-case O(1) query, expected O(1) updates. Study tip: Master sections 1–12 for interviews. Use section 13 for competitive programming or graduate-level coursework.