LeetCode patterns refer to common techniques or strategies used to solve coding problems on platforms like LeetCode. Recognizing and mastering these patterns can help you tackle a wide range of algorithmic challenges efficiently. Here are some key LeetCode patterns:
- Two Pointers:
- Use Case: Problems involving arrays, linked lists, or strings where you need to compare elements or find a pair.
- Example Problems: Find the pair with a given sum, remove duplicates from a sorted array.
- Sliding Window:
- Use Case: Problems that involve finding subarrays or substrings within a given window size.
- Example Problems: Maximum sum subarray of size k, longest substring without repeating characters.
- Fast and Slow Pointers:
- Use Case: Problems involving cycles in linked lists or arrays.
- Example Problems: Detect cycle in a linked list, find the middle of a linked list.
- Merge Intervals:
- Use Case: Problems involving overlapping intervals or intervals management.
- Example Problems: Merge overlapping intervals, insert interval.
- Cyclic Sort:
- Use Case: Problems where numbers are in a given range, typically 1 to n.
- Example Problems: Find the missing number, find all duplicates in an array.
- In-place Reversal of a LinkedList:
- Use Case: Problems that require reversing a part or whole of a linked list.
- Example Problems: Reverse a linked list, reverse nodes in k-group.
- Tree Depth First Search (DFS):
- Use Case: Problems that involve traversing a tree or graph deeply.
- Example Problems: Path sum, all paths for a sum.
- Tree Breadth First Search (BFS):
- Use Case: Problems that require level order traversal of a tree or graph.
- Example Problems: Level order traversal, minimum depth of a binary tree.
- Binary Search:
- Use Case: Problems that involve searching in a sorted array or finding an element efficiently.
- Example Problems: Find an element in a rotated array, search in a sorted array.
- Topological Sort:
- Use Case: Problems involving ordering tasks or nodes based on dependencies.
- Example Problems: Course schedule, alien dictionary.
- Dynamic Programming (DP):
- Use Case: Problems involving optimization and overlapping subproblems.
- Example Problems: Fibonacci sequence, knapsack problem, longest common subsequence.
- Backtracking:
- Use Case: Problems that involve exploring all potential solutions and choosing the optimal one.
- Example Problems: N-Queens, Sudoku solver, permutations.
- Union Find:
- Use Case: Problems involving connected components in a graph.
- Example Problems: Number of connected components, detect cycle in an undirected graph.
- Bit Manipulation:
- Use Case: Problems that involve manipulating bits to achieve the solution.
- Example Problems: Single number, count the number of 1 bits.
- Matrix Traversal:
- Use Case: Problems involving navigating or processing a 2D grid or matrix.
- Example Problems: Number of islands, search a 2D matrix.
- Greedy Algorithms:
- Use Case: Problems where local optimal choices lead to a global optimal solution.
- Example Problems: Interval scheduling, coin change problem, largest sum of non-adjacent numbers.
- Heap/Priority Queue:
- Use Case: Problems requiring frequent access to the smallest or largest element.
- Example Problems: Kth largest element in an array, merge k sorted lists.
- Prefix Sum:
- Use Case: Problems involving cumulative sums or differences within subarrays.
- Example Problems: Subarray sum equals k, range sum query.
- Counting and Hashing:
- Use Case: Problems involving frequency counts or hash maps for quick lookups.
- Example Problems: Two sum, group anagrams.
- Palindromic Substrings:
- Use Case: Problems involving identifying or counting palindromic substrings or subsequences.
- Example Problems: Longest palindromic substring, palindromic substrings count.
- Graph Traversal:
- Use Case: Problems involving traversal of graphs using DFS or BFS.
- Example Problems: Clone graph, shortest path in a binary matrix.
- Segment Tree:
- Use Case: Problems involving range queries and updates.
- Example Problems: Range sum query, range minimum query.
- Trie:
- Use Case: Problems involving efficient retrieval of words or prefixes from a dictionary.
- Example Problems: Word search II, implement a trie (prefix tree).
- Reservoir Sampling:
- Use Case: Problems that involve sampling random elements from a stream of unknown size.
- Example Problems: Random pick index, linked list random node.
- Monotonic Stack/Queue:
- Use Case: Problems where you need to maintain elements in a sorted order dynamically.
- Example Problems: Next greater element, sliding window maximum.
- Knapsack Pattern:
- Use Case: Problems that involve selection of items with constraints to maximize or minimize a value.
- Example Problems: 0/1 knapsack, partition equal subset sum.
- Combinatorial Search:
- Use Case: Problems that require generating combinations or permutations of elements.
- Example Problems: Combination sum, subsets, permutations.
- Disjoint Set (Union-Find):
- Use Case: Problems involving union and find operations to manage a collection of disjoint sets.
- Example Problems: Friend circles, number of connected components in an undirected graph.
- Cycle Detection in Graphs:
- Use Case: Problems that require detecting cycles in directed or undirected graphs.
- Example Problems: Course schedule II, detect cycle in a directed graph.
- Flood Fill Algorithm:
- Use Case: Problems involving region-based operations in matrices.
- Example Problems: Flood fill, number of enclaves.
- Binary Indexed Tree (Fenwick Tree):
- Use Case: Problems that involve efficient updates and queries on prefix sums.
- Example Problems: Range sum query, range sum and update.
- Divide and Conquer:
- Use Case: Problems that can be divided into smaller subproblems, solved independently, and combined.
- Example Problems: Merge sort, quicksort, closest pair of points.
- Reservoir Sampling:
- Use Case: Problems involving sampling k elements from a stream.
- Example Problems: Random pick index, linked list random node.
- Binary Search Tree (BST) Operations:
- Use Case: Problems involving operations on BSTs like insertion, deletion, and traversal.
- Example Problems: Validate BST, kth smallest element in a BST.
- Bitmasking:
- Use Case: Problems where you need to represent and manipulate subsets using bits.
- Example Problems: Subset sum, maximum product of word lengths.
- Dynamic Programming on Trees:
- Use Case: DP problems applied to tree structures, often using post-order traversal.
- Example Problems: House robber III, longest path in a tree.
- Matrix Exponentiation:
- Use Case: Problems involving efficient computation of large powers of matrices.
- Example Problems: Fibonacci sequence in logarithmic time.
- Meet in the Middle:
- Use Case: Problems that benefit from splitting into two halves and solving each half independently.
- Example Problems: Subset sum problem for large sets.
- Line Sweep Algorithm:
- Use Case: Problems involving processing events in a sorted order.
- Example Problems: Skyline problem, meeting rooms II.
- Eulerian Path and Circuit:
- Use Case: Problems involving finding paths in graphs that visit every edge exactly once.
- Example Problems: Reconstruct itinerary, valid arrangement of pairs.
- Bellman-Ford Algorithm:
- Use Case: Shortest path problems that handle negative weights.
- Example Problems: Shortest path in a graph with negative weights.
- Floyd-Warshall Algorithm:
- Use Case: Finding shortest paths between all pairs of vertices in a graph.
- Example Problems: All-pairs shortest path problem.
- Tarjan’s Algorithm:
- Use Case: Finding strongly connected components in a graph.
- Example Problems: Critical connections in a network.
- Hopcroft-Karp Algorithm:
- Use Case: Maximum bipartite matching problems.
- Example Problems: Maximum number of matching in bipartite graph.
- Shortest Path Faster Algorithm (SPFA):
- Use Case: Finding shortest paths in graphs, an optimization of Bellman-Ford.
- Example Problems: Shortest path in a graph with negative weights.
- Dynamic Connectivity:
- Use Case: Problems involving connectivity queries in dynamic graphs.
- Example Problems: Dynamic connectivity problem.
- Subset Sum with Memoization:
- Use Case: Problems involving checking possible subsets that meet certain conditions.
- Example Problems: Partition equal subset sum, target sum.
- Catalan Numbers:
- Use Case: Problems that count certain types of combinatorial structures.
- Example Problems: Number of unique BSTs, valid parentheses.
- Manacher’s Algorithm:
- Use Case: Finding the longest palindromic substring in linear time.
- Example Problems: Longest palindromic substring.
- Cycle Sort:
- Use Case: Finding duplicates in arrays where elements are in a known range.
- Example Problems: Find the duplicate number.
- Bitwise XOR for Inverse Operations:
- Use Case: Problems involving toggling and finding unique elements.
- Example Problems: Single number, two single numbers.
- Sparse Table:
- Use Case: Range query problems that require efficient querying with static data.
- Example Problems: Range minimum query, range maximum query.
- Suffix Array and Suffix Tree:
- Use Case: String processing problems involving efficient substring search.
- Example Problems: Longest common substring, repeated DNA sequences.
- Segment Trees with Lazy Propagation:
- Use Case: Problems involving range updates and queries.
- Example Problems: Range sum query with updates, range minimum query with updates.
- Heavy-Light Decomposition:
- Use Case: Efficiently answering queries on paths in trees.
- Example Problems: Path queries in trees.
- Mo’s Algorithm:
- Use Case: Answering offline range queries efficiently.
- Example Problems: Number of distinct elements in a range, range sum queries.
- KMP Algorithm:
- Use Case: String matching problems.
- Example Problems: Pattern search in a string.
- Aho-Corasick Algorithm:
- Use Case: Multiple pattern matching problems.
- Example Problems: Search multiple patterns in a text.
- Z-Algorithm:
- Use Case: Pattern matching and string preprocessing.
- Example Problems: Find all occurrences of a pattern in a text.
- Extended Euclidean Algorithm:
- Use Case: Problems involving finding modular inverses.
- Example Problems: Solve linear Diophantine equations.
- Minimum Spanning Tree (MST):
- Use Case: Problems involving connecting all points in a graph with the minimum total edge weight.
- Example Problems: Kruskal’s algorithm, Prim’s algorithm.
- Articulation Points and Bridges:
- Use Case: Finding critical nodes and edges in a graph whose removal would increase the number of connected components.
- Example Problems: Critical connections in a network, articulation points in a graph.
- Network Flow:
- Use Case: Problems involving maximum flow in networks.
- Example Problems: Ford-Fulkerson algorithm, Edmonds-Karp algorithm, maximum bipartite matching.
- Convex Hull:
- Use Case: Finding the smallest convex polygon that can enclose a set of points.
- Example Problems: Graham’s scan, Jarvis’s march.
- Graph Coloring:
- Use Case: Problems where you need to color vertices of a graph so that no two adjacent vertices share the same color.
- Example Problems: Map coloring, scheduling problems.
- Knuth-Morris-Pratt (KMP) Algorithm:
- Use Case: Efficient pattern matching in strings.
- Example Problems: Substring search, finding patterns in text.
- Union by Rank and Path Compression:
- Use Case: Optimizing the union-find algorithm.
- Example Problems: Dynamic connectivity, Kruskal’s MST algorithm.
- Hamiltonian Path and Circuit:
- Use Case: Problems involving finding a path or circuit that visits each vertex exactly once.
- Example Problems: Traveling salesman problem.
- Counting Inversions:
- Use Case: Counting the number of inversions in an array.
- Example Problems: Using merge sort to count inversions.
- Randomized Algorithms:
- Use Case: Algorithms that use a degree of randomness to solve problems.
- Example Problems: Randomized quicksort, Monte Carlo methods.
- Divide and Conquer for Convolution:
- Use Case: Efficiently multiplying large numbers or polynomials.
- Example Problems: Karatsuba algorithm, fast Fourier transform (FFT).
- Exponentiation by Squaring:
- Use Case: Efficiently computing large powers.
- Example Problems: Modular exponentiation, power of a number.
- Burnside’s Lemma:
- Use Case: Counting distinct objects under symmetry.
- Example Problems: Counting distinct colorings of a graph.
- Inclusion-Exclusion Principle:
- Use Case: Problems involving counting the number of elements in the union of several sets.
- Example Problems: Counting intersections of sets, derangements.
- Catalan Numbers and Combinatorial Counting:
- Use Case: Counting specific types of combinatorial structures.
- Example Problems: Number of valid parentheses expressions, number of BSTs.
- Fenwick Tree (Binary Indexed Tree):
- Use Case: Efficiently update elements and calculate prefix sums in a table of numbers.
- Example Problems: Range sum queries, dynamic prefix sums.
- Red-Black Trees and AVL Trees:
- Use Case: Self-balancing binary search trees.
- Example Problems: Maintaining a sorted list with insertions and deletions.
- Treap (Tree + Heap):
- Use Case: A randomized binary search tree with heap properties.
- Example Problems: Balanced binary search operations, order statistics.
- Suffix Automaton:
- Use Case: Solving problems related to substrings of a string efficiently.
- Example Problems: Longest common substring, number of distinct substrings.
- Planar Graph Algorithms:
- Use Case: Algorithms specifically designed for planar graphs.
- Example Problems: Planarity testing, face traversal.
- Cycle Detection in Directed Graphs:
- Use Case: Detecting cycles in a directed graph.
- Example Problems: Course scheduling, dependency resolution.
- 2-SAT Problem:
- Use Case: Solving certain types of boolean satisfiability problems.
- Example Problems: Implication graphs, variable assignments.
- Link/Cut Trees:
- Use Case: Dynamic tree data structure.
- Example Problems: Dynamic connectivity, dynamic tree queries.
- Persistent Data Structures:
- Use Case: Data structures that preserve the previous version of the data when it is modified.
- Example Problems: Versioned array, persistent segment trees.
- Range Minimum Query (RMQ):
- Use Case: Finding the minimum value in a subarray.
- Example Problems: Static RMQ, dynamic RMQ.
- Heavy-Light Decomposition (HLD):
- Use Case: Answering path queries efficiently in trees.
- Example Problems: Path sum queries, path maximum queries.
- Dynamic Programming on Graphs:
- Use Case: DP problems extended to graphs.
- Example Problems: Shortest path in DAG, longest path in DAG.
- Convex Hull Trick:
- Use Case: Optimizing dynamic programming problems with linear functions.
- Example Problems: Minimum cost paths, dynamic range queries.
- Sqrt Decomposition:
- Use Case: Breaking down a problem into manageable blocks for efficient querying and updating.
- Example Problems: Range sum queries, range minimum queries.
- Heavy Path Decomposition:
- Use Case: Decomposing trees for efficient query operations.
- Example Problems: Path queries in trees, subtree queries.
- Online Algorithms:
- Use Case: Algorithms that process input piece-by-piece in a serial fashion.
- Example Problems: Online caching, competitive algorithms.
- Quantum Algorithms:
- Use Case: Leveraging principles of quantum mechanics for problem-solving.
- Example Problems: Shor’s algorithm for factoring, Grover’s search algorithm.
- De Bruijn Sequences:
- Use Case: Sequences that represent all possible sequences of a given length.
- Example Problems: Sequence reconstruction, generating all binary strings.
- Automata Theory:
- Use Case: Designing and understanding computational models like finite state machines.
- Example Problems: Regular expression matching, parsing sequences.
- Probabilistic Data Structures:
- Use Case: Using probabilistic techniques to handle large data efficiently.
- Example Problems: Bloom filters, Count-Min sketch.
- Randomized Select:
- Use Case: Finding the k-th smallest/largest element in an unordered list.
- Example Problems: Quickselect algorithm.
- Game Theory:
- Use Case: Analyzing competitive situations to determine optimal strategies.
- Example Problems: Nim game, tic-tac-toe.
- Approximation Algorithms:
- Use Case: Finding near-optimal solutions to optimization problems.
- Example Problems: Traveling salesman problem, vertex cover.
- Branch and Bound:
- Use Case: Solving combinatorial and optimization problems by systematically exploring candidate solutions.
- Example Problems: 0/1 knapsack problem, traveling salesman problem.
- Polynomial Time Approximation Scheme (PTAS): – Use Case: Finding solutions within a factor of (1 + ε) of the optimal solution in polynomial time. – Example Problems: Euclidean traveling salesman problem, bin packing problem.
These 100 patterns and techniques cover a broad range of problem-solving strategies, each with its own set of applications and example problems. Mastery of these patterns can significantly enhance your ability to tackle a wide variety of coding challenges and algorithmic problems.
Search
Categories
- Algorithms 26
- Blockchain 3
- BQ-updates 10
- Development 20
- Employment 28
- Finance 5
- Security 9
- Spring 15
- Technology 7
Recent Posts
-
Understanding the Bin Packing Problem on LeetCode
-
Mastering Interval Scheduling: A Guide to the Interval Scheduling Problem on LeetCode
-
Understanding the Hamiltonian Path Problem on LeetCode
-
Mastering the Counting Inversions Problem on LeetCode
-
A Comprehensive Guide to Backtracking Algorithms on LeetCode