A comprehensive collection of essential Data Structures & Algorithms patterns
Pattern File Key Problems Time Complexity Two Pointers two_pointers.cpp3Sum, Container With Most Water O(n) Sliding Window sliding_window.cppLongest Substring, Subarray Sum O(n) Prefix Sum prefix_sum.cppRange Sum Query, Subarray Sum O(1) query Kadane's Algorithm kadane.cppMaximum Subarray, Maximum Product O(n)
Pattern File Key Problems Time Complexity Binary Search binary_search.cppSearch Insert Position, First/Last O(log n)
Sorting & Custom Comparators Backtracking & Combinatorics Pattern File Key Problems Time Complexity Binary Search binary_search.cppSearch Insert Position, First/Last O(log n)
Sorting & Custom Comparators Pattern File Key Problems Time Complexity Traversals traversals.cppInorder, Preorder, Postorder, Level Order O(n) LCA lca.cppLowest Common Ancestor O(log n) Tree DP tree_dp.cppDiameter, Path Sum, Subtree Queries O(n)
Pattern File Key Problems Time Complexity DFS/BFS dfs_bfs.cppConnected Components, Shortest Path O(V+E) Dijkstra dijkstra.cppShortest Path, Network Delay O(E log V) Union Find union_find.cppConnected Components, MST O(α(n)) Topological Sort topo_sort.cppCourse Schedule, Alien Dictionary O(V+E)
Pattern File Key Problems Time Complexity 1D DP dp_1d.cppFibonacci, Climbing Stairs, House Robber O(n) 2D DP dp_2d.cppUnique Paths, Edit Distance O(nm) LIS/LCS lis_lcs.cppLongest Increasing Subsequence O(n log n) Knapsack knapsack.cpp0/1 Knapsack, Coin Change O(nW)
Pattern File Key Problems Time Complexity GCD/LCM gcd_lcm.cppGreatest Common Divisor O(log min(a,b)) Prime Numbers primes.cppSieve, Primality Testing O(n log log n) Modular Arithmetic modular.cppFast Exponentiation, Modular Inverse O(log n)
Design Patterns (LeetCode Design Tag) Pattern File Key Problems Time Complexity CP Template cp_template.cppFast I/O, Common Macros, Debugging O(1) Common Utilities cp_template.cppGCD, Power, Modular Operations Varies
See cp_template.cpp for the complete template.
#include < bits/stdc++.h> using namespace std ;
#define ll long long
#define all (x ) x.begin(), x.end()
#define sz (x ) (int )x.size()
#define FAST ios_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
#define debug (x ) cerr << #x << " = " << (x) << " \n "
#else
#define debug (x )
#endif int main () {
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 " ;
}
return 0 ;
} // .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"
}# 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 Read & Understand (2-3 min)
Identify input/output format Find constraints and edge cases Look for patterns in examples 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 Implementation (10-15 min)
Use templates from this repository Focus on correctness first, then optimize Handle edge cases Testing (2-3 min)
Test with given examples Think of edge cases Dry run with small inputs // 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
#define all (x ) x.begin(), x.end()
#define sz (x ) (int )x.size()Pattern Recognition Guide Problem Type Common Keywords Suggested 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
// 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 ;
}Algorithm Best Average Worst Space Linear Search O(1) O(n) O(n) O(1) Binary Search O(1) O(log n) O(log n) O(1) Quick Sort O(n log n) O(n log n) O(n²) O(log n) Merge Sort O(n log n) O(n log n) O(n log n) O(n) Heap Sort O(n log n) O(n log n) O(n log n) O(1) DFS/BFS O(V + E) O(V + E) O(V + E) O(V) Dijkstra O(E log V) O(E log V) O(E log V) O(V)
Data Structure Operations Data Structure Access Search Insert Delete Space Array O(1) O(n) O(n) O(n) O(n) Hash Table O(1) O(1) O(1) O(1) O(n) Binary Tree O(log n) O(log n) O(log n) O(log n) O(n) Heap O(1) O(n) O(log n) O(log n) O(n) Segment Tree O(log n) O(log n) O(log n) O(log n) O(n)
// 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!)Fork the repository Add new patterns or improve existing ones Ensure code follows the template format Add relevant LeetCode problem links Submit a pull request ⭐ Star this repository if it helped you in your competitive programming journey! ⭐