Skip to content

Repository files navigation

DSA Patterns Cheatsheet

C++17LeetCodeCodeforces

A comprehensive collection of essential Data Structures & Algorithms patterns


Table of Contents


Pattern Categories

Arrays & Strings

PatternFileKey ProblemsTime Complexity
Two Pointerstwo_pointers.cpp3Sum, Container With Most WaterO(n)
Sliding Windowsliding_window.cppLongest Substring, Subarray SumO(n)
Prefix Sumprefix_sum.cppRange Sum Query, Subarray SumO(1) query
Kadane's Algorithmkadane.cppMaximum Subarray, Maximum ProductO(n)

String Patterns

PatternFileKey ProblemsTime Complexity
Hash Maps & Anagramsstring_patterns.cppGroup Anagrams, Two SumO(n)
Sliding Windowstring_patterns.cppMin Window SubstringO(n)
KMP Algorithmstring_patterns.cppPattern MatchingO(n+m)
Rolling Hashstring_patterns.cppRabin-Karp, Longest PrefixO(n)

Data Structures

PatternFileKey ProblemsTime Complexity
Stack & Queuestack_queue.cppValid Parentheses, Min StackO(1) ops
Linked Listslinkedlist.cppReverse List, Detect CycleO(n)
Heaps & Priority Queueheap_priority_queue.cppTop K, Merge K ListsO(log n) ops
Trie (Prefix Tree)trie.cppWord Search II, Auto-completeO(m) ops

Binary Search

PatternFileKey ProblemsTime Complexity
Binary Searchbinary_search.cppSearch Insert Position, First/LastO(log n)

Sorting & Custom Comparators

PatternFileKey ProblemsTime Complexity
Sorting Algorithmssorting_algorithms.cppQuick Sort, Merge Sort, Heap SortO(n log n)
Custom Comparatorssorting_algorithms.cppMerge Intervals, Meeting RoomsO(n log n)

Matrix & 2D Arrays

PatternFileKey ProblemsTime Complexity
Matrix Traversalmatrix_patterns.cppSpiral Matrix, Rotate ImageO(mn)
Matrix Searchmatrix_patterns.cppSearch 2D MatrixO(log mn)
Island Problemsmatrix_patterns.cppNumber of Islands, Max AreaO(mn)

Backtracking & Combinatorics

PatternFileKey ProblemsTime Complexity
Generate Allbacktracking_patterns.cppSubsets, PermutationsO(2^n)
Constraint Satisfactionbacktracking_patterns.cppN-Queens, Sudoku SolverO(b^d)
Word Searchbacktracking_patterns.cppWord Search, Palindrome PartitionO(4^mn)

Bit Manipulation

PatternFileKey ProblemsTime Complexity
XOR Propertiesbit_patterns.cppSingle Number, Missing NumberO(n)
Bit Operationsbit_patterns.cppPower of Two, Reverse BitsO(1)
Subset Generationbit_patterns.cppGenerate Subsets using BitsO(2^n)

Binary Search

PatternFileKey ProblemsTime Complexity
Binary Searchbinary_search.cppSearch Insert Position, First/LastO(log n)

Sorting & Custom Comparators

PatternFileKey ProblemsTime Complexity
Sorting Algorithmssorting_algorithms.cppQuick Sort, Merge Sort, Heap SortO(n log n)
Custom Comparatorssorting_algorithms.cppMerge Intervals, Meeting RoomsO(n log n)

Trees

PatternFileKey ProblemsTime Complexity
Traversalstraversals.cppInorder, Preorder, Postorder, Level OrderO(n)
LCAlca.cppLowest Common AncestorO(log n)
Tree DPtree_dp.cppDiameter, Path Sum, Subtree QueriesO(n)

Graphs

PatternFileKey ProblemsTime Complexity
DFS/BFSdfs_bfs.cppConnected Components, Shortest PathO(V+E)
Dijkstradijkstra.cppShortest Path, Network DelayO(E log V)
Union Findunion_find.cppConnected Components, MSTO(α(n))
Topological Sorttopo_sort.cppCourse Schedule, Alien DictionaryO(V+E)

Dynamic Programming

PatternFileKey ProblemsTime Complexity
1D DPdp_1d.cppFibonacci, Climbing Stairs, House RobberO(n)
2D DPdp_2d.cppUnique Paths, Edit DistanceO(nm)
LIS/LCSlis_lcs.cppLongest Increasing SubsequenceO(n log n)
Knapsackknapsack.cpp0/1 Knapsack, Coin ChangeO(nW)

Greedy Algorithms

PatternFileKey ProblemsTime Complexity
Interval Schedulinggreedy_patterns.cppMeeting Rooms, Merge IntervalsO(n log n)
Greedy Choicegreedy_patterns.cppJump Game, Gas StationO(n)
Optimizationgreedy_patterns.cppMinimum Cost, Maximum ProfitO(n log n)

Game Theory

PatternFileKey ProblemsTime Complexity
Minimaxgame_theory_patterns.cppStone Game, Predict WinnerO(n²)
Nim Gamesgame_theory_patterns.cppNim Game, Stone Game IIO(n)
Zero-Sum Gamesgame_theory_patterns.cppOptimal Strategy, Game WinningO(n²)

Math & Number Theory

PatternFileKey ProblemsTime Complexity
GCD/LCMgcd_lcm.cppGreatest Common DivisorO(log min(a,b))
Prime Numbersprimes.cppSieve, Primality TestingO(n log log n)
Modular Arithmeticmodular.cppFast Exponentiation, Modular InverseO(log n)

Design Patterns (LeetCode Design Tag)

PatternFileKey ProblemsTime Complexity
Cache Systemsdesign_patterns.cppLRU Cache, LFU Cache, Time-Based KVO(1) ops
Data Structuresdesign_patterns.cppStack/Queue, HashSet/HashMap, TrieO(1) - O(log n)
Iteratorsdesign_patterns.cppBST Iterator, Peeking IteratorO(1) amortized
Specializeddesign_patterns.cppHit Counter, Twitter, Snake GameVaries

Advanced Data Structures

PatternFileKey ProblemsTime Complexity
Segment Treesegment_tree.cppRange Sum/Min/Max QueryO(log n)
Fenwick Treefenwick_tree.cppRange Sum, Inversion CountO(log n)

System Design Patterns

PatternFileKey ProblemsTime Complexity
LRU Cachesystem_design_patterns.cppLRU Cache, LFU CacheO(1) ops
Rate Limitersystem_design_patterns.cppToken Bucket, Sliding WindowO(1)
Consistent Hashingsystem_design_patterns.cppLoad Balancing, Distributed SystemsO(log n)

Template & Utilities

PatternFileKey ProblemsTime Complexity
CP Templatecp_template.cppFast I/O, Common Macros, DebuggingO(1)
Common Utilitiescp_template.cppGCD, Power, Modular OperationsVaries

Template & Setup

Optimized CP Template

See cp_template.cpp for the complete template.

#include<bits/stdc++.h>usingnamespacestd;
#definelllonglong
#defineall(x) x.begin(), x.end()
#definesz(x) (int)x.size()
#defineFASTios_base::sync_with_stdio(false); cin.tie(nullptr);
ll gcd(ll a, ll b) {
return b == 0 ? a : gcd(b, a % b);
}
// Debug helper (works only in local environment)
#ifdef DEBUG
#definedebug(x) cerr << #x << " = " << (x) << "\n"
#else
#definedebug(x)
#endifintmain() {
FAST;
int t;
cin >> t;
while(t--) {
int n;
cin >> n;
vector<int> arr(n);
for(auto &x : arr) cin >> x;
sort(all(arr));
for(auto x : arr)
cout << x << "";
cout << "\n";
}
return0;
}

VS Code Setup for CP

// .vscode/settings.json
{
"files.associations": {
"*.cpp": "cpp"
},
"code-runner.executorMap": {
"cpp": "cd $dir && g++ -std=c++17 -O2 -o $fileNameWithoutExt $fileName && ./$fileNameWithoutExt"
},
"code-runner.runInTerminal": true,
"C_Cpp.default.cppStandard": "c++17"
}

Compilation Commands

# For competitive programming (optimized)
g++ -std=c++17 -O2 -Wall -Wextra -o solution solution.cpp
# For debugging
g++ -std=c++17 -g -DLOCAL -o solution solution.cpp
# One-liner for contestsalias cpr="g++ -std=c++17 -O2 -o sol"

Competitive Programming Tips

Problem-Solving Strategy

  1. Read & Understand (2-3 min)

    • Identify input/output format
    • Find constraints and edge cases
    • Look for patterns in examples
  2. Pattern Recognition (1-2 min)

    • Array/String → Two pointers, Sliding window
    • Tree/Graph → DFS/BFS, DP on trees
    • Optimization → DP, Greedy, Binary search
    • Range queries → Segment tree, Fenwick tree
  3. Implementation (10-15 min)

    • Use templates from this repository
    • Focus on correctness first, then optimize
    • Handle edge cases
  4. Testing (2-3 min)

    • Test with given examples
    • Think of edge cases
    • Dry run with small inputs

Time-Saving Tricks

// Fast I/O for large inputsios::sync_with_stdio(false);
cin.tie(nullptr);
// Vector initialization shortcuts
vector<int> dp(n, -1); // Initialize with -1
vector<vector<int>> grid(n, vector<int>(m, 0)); // 2D grid// STL shortcutssort(all(v)); // Sort entire vectorreverse(all(v)); // Reverse vector
v.erase(unique(all(v)), v.end()); // Remove duplicates// Common patterns
#defineall(x) x.begin(), x.end()
#definesz(x) (int)x.size()

Common Patterns

Pattern Recognition Guide

Problem TypeCommon KeywordsSuggested Approach
Two Sum/Pair"pair", "two elements", "target sum"Two pointers, Hash map
Subarray/Substring"contiguous", "subarray", "substring"Sliding window, Prefix sum
Path/Connection"path", "connected", "reachable"DFS/BFS, Union Find
Optimization"minimum", "maximum", "optimal"DP, Greedy, Binary search
Range Query"range", "interval", "segment"Segment tree, Fenwick tree
Counting"count", "number of ways"DP, Combinatorics

Mental Models

// Two Pointers Templateint left = 0, right = n - 1;
while (left < right) {
if (condition) left++;
else right--;
}
// Sliding Window Templateint left = 0, right = 0;
while (right < n) {
// Expand windowwhile (invalid_condition) {
// Shrink window
left++;
}
// Update answer
right++;
}
// Binary Search Templateint left = 0, right = n;
while (left < right) {
int mid = left + (right - left) / 2;
if (check(mid)) right = mid;
else left = mid + 1;
}

Complexity Cheatsheet

Time Complexities

AlgorithmBestAverageWorstSpace
Linear SearchO(1)O(n)O(n)O(1)
Binary SearchO(1)O(log n)O(log n)O(1)
Quick SortO(n log n)O(n log n)O(n²)O(log n)
Merge SortO(n log n)O(n log n)O(n log n)O(n)
Heap SortO(n log n)O(n log n)O(n log n)O(1)
DFS/BFSO(V + E)O(V + E)O(V + E)O(V)
DijkstraO(E log V)O(E log V)O(E log V)O(V)

Data Structure Operations

Data StructureAccessSearchInsertDeleteSpace
ArrayO(1)O(n)O(n)O(n)O(n)
Hash TableO(1)O(1)O(1)O(1)O(n)
Binary TreeO(log n)O(log n)O(log n)O(log n)O(n)
HeapO(1)O(n)O(log n)O(log n)O(n)
Segment TreeO(log n)O(log n)O(log n)O(log n)O(n)

Constraint Guidelines

// n <= 10^8: O(log n), O(1)// n <= 10^6: O(n), O(n log n)// n <= 10^4: O(n²)// n <= 500: O(n³)// n <= 20: O(2^n), O(n!)// n <= 10: O(n!)

Resources

Learning Platforms

Reference Materials

Tools & Extensions


Contributing

  1. Fork the repository
  2. Add new patterns or improve existing ones
  3. Ensure code follows the template format
  4. Add relevant LeetCode problem links
  5. Submit a pull request

⭐ Star this repository if it helped you in your competitive programming journey! ⭐

About

A comprehensive collection of essential Data Structures & Algorithms patterns

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages