This repository contains a collection of the most common patterns used to solve LeetCode problems efficiently.
Each pattern includes:
- When to use it
- A representative problem
- Input/Output example
- An optimized Python solution (best possible time/space complexity)
- Step-by-step explanation of the approach
| # | Pattern | Typical Use Case | Example Problem |
|---|---|---|---|
| 1 | Two Pointers | Sorted arrays, palindromes, target sums | Two Sum II |
| 2 | Sliding Window | Subarrays/substrings with constraints | Longest Substring Without Repeating Characters |
| 3 | Fast & Slow Pointers | Detect cycles, find middle node | Linked List Cycle II |
| 4 | Binary Search | Sorted arrays, monotonic conditions | Find First and Last Position of Element |
| 5 | Backtracking / DFS | Subsets, permutations, combinations | Subsets |
| 6 | Breadth-First Search (BFS) | Level-order traversal, shortest paths | Binary Tree Level Order Traversal |
| 7 | Dynamic Programming (DP) | Optimization with overlapping subproblems | House Robber |
| 8 | Hash Tables | Fast lookup, complement check | Two Sum |
| 9 | Monotonic Stack | Next greater/smaller elements | Daily Temperatures |
| 10 | Heap / Priority Queue | Top-k, merging sorted lists | Kth Largest Element |
| 11 | Union-Find (DSU) | Connected components, cycle detection | Connected Components in Graph |
| 12 | Trie (Prefix Tree) | Prefix search, autocomplete | Implement Trie |
| 13 | Bit Manipulation | Unique elements, subset states | Single Number |
| 14 | Merge Intervals | Overlapping intervals, scheduling | Merge Intervals |
| 15 | Topological Sort | Dependency resolution, scheduling | Course Schedule |
Leetcode Pattern Recognition Guide
Leetcode Pattern Recognition Guide PDF
Problem: Two Sum II (input sorted)
- Input:
numbers = [2,7,11,15], target = 9 - Output:
[1,2](1-based indices)
def two_sum_sorted(numbers, target):
l, r = 0, len(numbers) - 1
while l < r:
s = numbers[l] + numbers[r]
if s == target:
return [l+1, r+1]
if s < target:
l += 1
else:
r -= 1
return [-1, -1]- Time Complexity:
O(n) - Space Complexity:
O(1)
- Start with two pointers (
lat beginning,rat end). - Check the sum:
- If equal β return indices.
- If less β move
lright. - If greater β move
rleft.
- Continue until they meet.
Each pattern in this repo follows the same structure:
- When to use
- Problem statement with I/O
- Optimized Python code
- Complexity analysis
- Step-by-step explanation
The goal of this repository is to:
- Provide a practical reference for mastering LeetCode patterns.
- Help developers recognize problem types quickly.
- Offer clean, optimized Python implementations.
Feel free to:
- Add new problems under existing patterns.
- Suggest improvements in code or explanations.
- Submit pull requests with additional patterns.
