DSA PATTERN-WISE MASTER SHEET ✅

45860
Aug 31, 2026
Sep 09, 2026

🚀 DSA PATTERN-WISE MASTER SHEET - CHATGPT CREATED - Note That -

📌 Master DSA Patterns

#PatternPriority
1Hashing / Frequency Map⭐⭐⭐⭐⭐
2Two Pointers⭐⭐⭐⭐⭐
3Sliding Window⭐⭐⭐⭐⭐
4Prefix Sum⭐⭐⭐⭐⭐
5Difference Array⭐⭐⭐
6Kadane's Algorithm⭐⭐⭐⭐
7Binary Search⭐⭐⭐⭐⭐
8Binary Search on Answer⭐⭐⭐⭐⭐
9Sorting + Greedy⭐⭐⭐⭐⭐
10Fast & Slow Pointers⭐⭐⭐⭐
11Stack⭐⭐⭐⭐⭐
12Monotonic Stack⭐⭐⭐⭐⭐
13Monotonic Queue / Deque⭐⭐⭐⭐
14Heap / Priority Queue⭐⭐⭐⭐⭐
15Top K Elements⭐⭐⭐⭐⭐
16Merge Intervals⭐⭐⭐⭐
17Cyclic Sort⭐⭐⭐⭐
18Linked List Reversal⭐⭐⭐⭐
19Tree DFS⭐⭐⭐⭐⭐
20Tree BFS⭐⭐⭐⭐⭐
21Tree Construction / Recursion⭐⭐⭐⭐
22BST Patterns⭐⭐⭐⭐
23Graph DFS⭐⭐⭐⭐⭐
24Graph BFS⭐⭐⭐⭐⭐
25Multi-Source BFS⭐⭐⭐⭐
26Topological Sort⭐⭐⭐⭐⭐
27Union Find / DSU⭐⭐⭐⭐
28Shortest Path⭐⭐⭐⭐⭐
29Backtracking⭐⭐⭐⭐⭐
301D Dynamic Programming⭐⭐⭐⭐⭐
312D Dynamic Programming⭐⭐⭐⭐⭐
32Knapsack DP⭐⭐⭐⭐⭐
33LCS / String DP⭐⭐⭐⭐
34LIS / Subsequence DP⭐⭐⭐⭐
35Interval DP⭐⭐⭐
36Greedy⭐⭐⭐⭐⭐
37Trie⭐⭐⭐⭐
38Bit Manipulation⭐⭐⭐⭐
39Matrix / Grid⭐⭐⭐⭐⭐
40Divide & Conquer⭐⭐⭐⭐

🔥 SLIDING WINDOW — COMPLETE PATTERN SHEET

Master idea: Expand right → maintain window state → if invalid, move left → update answer/count.

Sliding Window is mainly used for subarrays/substrings, especially problems involving longest, shortest, count, fixed K, at most K, exactly K, at least K, frequencies, or window constraints.

🔗 Sliding Window Patterns — LeetCode

🔗 Complete Sliding Window Pattern Sheet


📚 USEFUL LEETCODE REFERENCES

🔗 Sliding Window Patterns

🔗 Complete Sliding Window Revision

🔗 Sliding Window Complete Pattern Sheet

🔗 DSA All Pattern-Wise Master Sheet

🔗 C++ STL Containers Cheat Sheet

🔗 50+ Useful C++ Functions


Provided link Of All Problems in Bottom 🔽 Check Bottom


🟢 1. TWO POINTER

1. Problem Number + Name

  • 11 — Container With Most Water
  • 15 — 3Sum
  • 16 — 3Sum Closest
  • 18 — 4Sum
  • 167 — Two Sum II
  • 453 — Minimum Moves to Equal Array Elements
  • 462 — Minimum Moves to Equal Array Elements II
  • 881-type pattern — K-Sum
  • 1679 — Max Number of K-Sum Pairs
  • 2491 — Divide Players Into Teams of Equal Skill
  • 2563 — Count the Number of Fair Pairs
  • 2401 — Longest Nice Subarray

Use LeetCode problem number directly.

2.0 All Approaches —

  • Two Pointer
  • Sorting + Two Pointer
  • HashMap
  • Binary Search

3. Core / Key Idea

Move left and right based on whether the current condition is too small/large.

4. Approach Name

Opposite Direction Two Pointer

5. When to Use

🔑 Keywords:

  • sorted array
  • pair
  • triplet
  • closest
  • target sum
  • maximize/minimize

6. Steps

sort
left = 0
right = n-1

while left < right:
    check condition
    move left/right

7. Time Complexity

O(n log n) after sorting
or O(n) if already sorted.


🟢 2. SLIDING WINDOW

Problems

  • 3 — Longest Substring Without Repeating Characters
  • 209 — Minimum Size Subarray Sum
  • 395 — Longest Substring with At Least K Repeating Characters
  • 424 — Longest Repeating Character Replacement
  • 713 — Subarray Product Less Than K
  • 904 — Fruit Into Baskets
  • 1004 — Max Consecutive Ones III
  • 1343 — Number of Sub-arrays of Size K
  • 1438 — Longest Continuous Subarray
  • 1456 — Maximum Number of Vowels
  • 2390 — Removing Stars (stack pattern)
  • 2405 — Optimal Partition of String
  • 2461 — Maximum Sum of Distinct Subarrays
  • 2958 — Longest Subarray With at Most K Frequency
  • 3305 — Vowels + K Consonants I
  • 3306 — Vowels + K Consonants II
  • 3254 / 3255 — Power of K-Size Subarrays
  • 3708 — Longest Fibonacci Subarray
  • 4032 — Longest Subarray With at Most K Distinct Prime Factors

3. Core Idea

Maintain a valid window:

[left ........ right]

Expand with right; shrink with left when invalid.

4. Approach

Variable Size Sliding Window

5. Recognition

🔑

  • longest substring
  • shortest subarray
  • at most K
  • exactly K
  • frequency
  • consecutive
  • window of size K

6. Steps

left = 0;

for (int right = 0; right < n; right++) {
    add(nums[right]);

    while (window_invalid) {
        remove(nums[left]);
        left++;
    }

    update_answer();
}

7. Complexity

O(n)


🟢 3. FIXED SIZE SLIDING WINDOW

Problems

  • 1343 — Number of Sub-arrays of Size K
  • 1456 — Maximum Number of Vowels in a Substring of Given Length
  • 2090 — K Radius Subarray Averages
  • 3254 — Find the Power of K-Size Subarrays I
  • 3255 — Find the Power of K-Size Subarrays II
  • 2461 — Maximum Sum of Distinct Subarrays With Length K

Core Idea

Window size must remain exactly K.

if (right - left + 1 > k)
    remove(nums[left++]);

Complexity

O(n)


🟢 4. HASHMAP / HASHSET

Problems

  • 1-type pattern / Two Sum
  • 128 — Longest Consecutive Sequence
  • 217-type duplicate pattern
  • 2195 — Append K Integers
  • 2295 — Replace Elements in an Array
  • 2442 — Count Distinct Integers After Reverse Operations
  • 287 — Find the Duplicate Number
  • 347 — Top K Frequent Elements
  • 451 — Sort Characters By Frequency
  • 523 — Continuous Subarray Sum
  • 560 — Subarray Sum Equals K
  • 692 — Top K Frequent Words
  • 792 — Number of Matching Subsequences
  • 1343 — fixed-window frequency
  • 1657-type frequency pattern
  • 2085-type frequency pattern
  • 2958 — At Most K Frequency
  • 3016 — Minimum Number of Pushes
  • 3305 / 3306 — Vowels
  • 3747 — Count Distinct Integers After Removing Zeros
  • 3761 — Mirror Pairs
  • 3889 — Mirror Frequency Distance

Core Idea

Store:

value → frequency
value → index
prefix → frequency
character → frequency

Recognition

🔑

  • frequency
  • duplicate
  • count
  • occurrence
  • lookup
  • complement
  • last position

Complexity

Average O(n)


🟢 5. PREFIX SUM

Problems

  • 523 — Continuous Subarray Sum
  • 525 — Contiguous Array
  • 560 — Subarray Sum Equals K
  • 2270 — Number of Ways to Split Array
  • 3747-type prefix counting
  • 3969 — Valid Subarrays With Matching Sum Digits

Core Idea

For:

prefix[j] - prefix[i] = target

Use HashMap.

Recognition

🔑

  • subarray sum
  • range sum
  • sum equals K
  • divisible by K
  • count subarrays

Complexity

O(n)


🟢 6. BINARY SEARCH

Problems

  • 33 — Search in Rotated Sorted Array
  • 34 — Find First and Last Position
  • 81 — Search in Rotated Sorted Array II
  • 153 — Find Minimum in Rotated Sorted Array
  • 162 — Find Peak Element
  • 540 — Single Element in a Sorted Array
  • 852 — Peak Index in a Mountain Array
  • 1901 — Find a Peak Element II
  • 2517 — Maximum Tastiness of Candy Basket
  • 3720 — Lexicographically Smallest Permutation Greater Than Target
  • 3932 — Count K-th Roots in a Range
  • 4032-type optimization patterns

Core Idea

Search space is monotonic.

left ---- mid ---- right

Recognition

🔑

  • sorted
  • minimum possible
  • maximum possible
  • first/last
  • peak
  • rotated
  • answer optimization

Complexity

O(log n)

For binary-search-on-answer:

O(n log answer)


🟢 7. SORTING

Problems

  • 75 — Sort Colors
  • 912 — Sort an Array
  • 215 — Kth Largest Element
  • 347 — Top K Frequent Elements
  • 451 — Sort Characters By Frequency
  • 692 — Top K Frequent Words
  • 324 — Wiggle Sort II
  • 2149 — Rearrange Array Elements by Sign
  • 2295 — Replace Elements
  • 2491 — Divide Players
  • 2563 — Fair Pairs
  • 3760 — Maximum Substrings
  • 3818 — Minimum Prefix Removal

Core Idea

Sort first when ordering simplifies the problem.

Recognition

🔑

  • smallest/largest
  • pair/triplet
  • frequency ordering
  • intervals
  • greedy after sorting

Complexity

O(n log n)


🟢 8. STACK / MONOTONIC STACK

Problems

  • 20-type Valid Parentheses
  • 42-type Trapping Rain Water
  • 84-type Largest Rectangle
  • 150 — Evaluate Reverse Polish Notation
  • 394 — Decode String
  • 402 — Remove K Digits
  • 503 — Next Greater Element II
  • 556 — Next Greater Element III
  • 678 — Valid Parenthesis String
  • 739 — Daily Temperatures
  • 921 — Minimum Add to Make Parentheses Valid
  • 1209 — Remove All Adjacent Duplicates II
  • 1381-type custom stack
  • 2390 — Removing Stars
  • 2104 — Sum of Subarray Ranges
  • 3746 — Minimum String Length After Balanced Removals

Core Idea

Use stack when the previous/next greater/smaller element matters.

Recognition

🔑

  • next greater
  • next smaller
  • remove elements
  • parentheses
  • nested
  • previous greater
  • monotonic

Complexity

Usually O(n)


🟢 9. GREEDY

Problems

  • 45 — Jump Game II
  • 55 — Jump Game
  • 738 — Monotone Increasing Digits
  • 769 — Max Chunks To Make Sorted
  • 846 — Hand of Straights
  • 1338 — Reduce Array Size to Half
  • 1481 — Least Number of Unique Integers
  • 2244 — Minimum Rounds
  • 2870 — Minimum Operations to Make Array Empty
  • 3016 — Minimum Number of Pushes
  • 324-type sorting/greedy
  • 3974 — Maximum Total Sum
  • 3979 — Maximum Valid Pair Sum

Core Idea

Make the best local decision that leads to the global optimum.

Recognition

🔑

  • minimum operations
  • maximum possible
  • choose largest/smallest
  • scheduling
  • intervals
  • jumps

Complexity

Usually O(n) or O(n log n)


🟢 10. BACKTRACKING

Problems

  • 17 — Letter Combinations of Phone Number
  • 22 — Generate Parentheses
  • 39 — Combination Sum
  • 40 — Combination Sum II
  • 46 — Permutations
  • 47 — Permutations II
  • 77 — Combinations
  • 78 — Subsets
  • 90 — Subsets II
  • 131 — Palindrome Partitioning
  • 216 — Combination Sum III
  • 301-type parentheses
  • 491 — Non-decreasing Subsequences
  • 698 — Partition to K Equal Sum Subsets
  • 784 — Letter Case Permutation
  • 980-type grid backtracking
  • Matchsticks to Square

Core Idea

choose
→ explore
→ undo

Recognition

🔑

  • all combinations
  • all permutations
  • all subsets
  • generate
  • partition
  • choose K

Complexity

Usually exponential:

O(2ⁿ) / O(n!)


🟢 11. DYNAMIC PROGRAMMING

Problems

  • 62 — Unique Paths
  • 63 — Unique Paths II
  • 64 — Minimum Path Sum
  • 70-type Climbing Stairs
  • 151-type / string DP
  • 198-type House Robber
  • 300 — Longest Increasing Subsequence
  • 322 — Coin Change
  • 377 — Combination Sum IV
  • 416 — Partition Equal Subset Sum
  • 494 — Target Sum
  • 518 — Coin Change II
  • 698 — Partition to K Equal Sum Subsets
  • 901-type state problems
  • 152 — Maximum Product Subarray
  • 1749 — Maximum Absolute Sum
  • 3693 — Climbing Stairs II
  • 3708 — Longest Fibonacci Subarray

Core Idea

Break into overlapping subproblems.

dp[state] = best/count answer for state

Recognition

🔑

  • maximum/minimum
  • number of ways
  • choose/not choose
  • subsequence
  • paths
  • target sum
  • coin

Complexity

Usually O(n), O(n²), or O(n × target).


🟢 12. LINKED LIST

Problems

  • 2 — Add Two Numbers
  • 19 — Remove Nth Node From End
  • 24 — Swap Nodes in Pairs
  • 82 — Remove Duplicates II
  • 92 — Reverse Linked List II
  • 138-type Copy List
  • 142 — Linked List Cycle II
  • 143 — Reorder List
  • 148 — Sort List
  • 206-type Reverse Linked List
  • 2095 — Delete Middle Node
  • 2130 — Maximum Twin Sum
  • 237 — Delete Node
  • 2487 — Remove Nodes
  • 3217 — Delete Nodes Present in Array

Core Patterns

  • Fast & Slow Pointer
  • Dummy Node
  • Reverse Linked List
  • Merge
  • Cycle Detection

Recognition

🔑

  • linked list
  • cycle
  • nth from end
  • reverse
  • middle
  • reorder

Complexity

Usually O(n).


🟢 13. BINARY TREE / BST

Problems

  • 94-type inorder
  • 102 — Binary Tree Level Order Traversal
  • 107 — Level Order Traversal II
  • 1161 — Maximum Level Sum
  • 129 — Sum Root to Leaf Numbers
  • 222 — Count Complete Tree Nodes
  • 230 — Kth Smallest Element in BST
  • 2471 — Minimum Operations to Sort Binary Tree by Level
  • 2583 — Kth Largest Sum in Binary Tree

Core Patterns

DFS
BFS
Inorder
Preorder
Postorder
Level Order

Recognition

🔑

  • tree
  • level
  • depth
  • path
  • root-to-leaf
  • BST
  • kth smallest/largest

Complexity

O(n)


🟢 14. GRAPH / GRID

Problems

  • 200 — Number of Islands
  • 547 — Number of Provinces
  • 2471-type tree/graph traversal
  • 2257 — Count Unguarded Cells
  • 3969-type grid
  • 1901 — Peak Element II

Core Patterns

  • DFS
  • BFS
  • Flood Fill
  • Connected Components
  • Matrix traversal

Recognition

🔑

  • islands
  • connected
  • adjacent
  • grid
  • province
  • path

Complexity

Usually O(V + E) or O(rows × cols).


🟢 15. BIT MANIPULATION ⭐

You have worked heavily on this area.

Problems

  • 137 — Single Number II
  • 260 — Single Number III
  • 421 — Maximum XOR
  • 477 — Total Hamming Distance
  • 1318 — Minimum Flips OR
  • 1780 — Sum of Powers of Three (base representation)
  • 1980 — Find Unique Binary String
  • 2044 — Maximum Bitwise OR Subsets
  • 2997 — Minimum Operations XOR Equal K
  • 3702 — Longest Subsequence With Non-Zero XOR
  • 3918 — Sum of Primes...
  • 4036 — Lexicographically Largest String...
  • 2401 — Longest Nice Subarray

Core Idea

Know these:

n & 1
n >> 1
n << 1
a ^ b
a & b
a | b
~a

Most Important Tricks

x ^ x = 0
x ^ 0 = x

Power of 2:

n > 0 && (n & (n - 1)) == 0

Set bit:

n | (1 << i)

Clear bit:

n & ~(1 << i)

Check bit:

n & (1 << i)

Complexity

Usually O(n × bits) → effectively O(n).


🟢 16. STRING

Problems

  • 3 — Longest Substring Without Repeating
  • 43 — Multiply Strings
  • 151 — Reverse Words
  • 2904 — Beautiful String
  • 1839 — Longest Beautiful Substring
  • 2405 — Optimal Partition
  • 2981 — Special Substring
  • 3016 — Minimum Pushes
  • 3720 — Lexicographically Smallest Permutation
  • 3746 — Balanced Removals
  • 3756 — Concatenate Non-Zero Digits
  • 3760 — Maximum Substrings
  • 4036 — Lexicographically Largest String
  • 3305 / 3306 — Vowel Substrings

Common Techniques

  • Frequency array
  • HashMap
  • Sliding Window
  • Stack
  • Two Pointer
  • String building
  • Lexicographical comparison

🟢 17. MATH / NUMBER THEORY

Problems

  • 7 — Reverse Integer
  • 29 — Divide Two Integers
  • 43 — Multiply Strings
  • 172 — Factorial Trailing Zeroes
  • 453 — Minimum Moves
  • 462 — Minimum Moves II
  • 1780 — Sum of Powers of Three
  • 3918 — Sum of Primes
  • 3974 — Maximum Total Sum
  • 3979 — Maximum Valid Pair Sum
  • 3747 — Distinct Integers
  • 3932 — K-th Roots
  • 3723 — Maximum Sum of Squares

Must Know

GCD
LCM
Prime
Sieve
Modulo
Power
Binary conversion
Decimal ↔ Binary
Decimal ↔ Hexadecimal

🟢 18. HEAP / PRIORITY QUEUE

Problems

  • 215 — Kth Largest Element
  • 347 — Top K Frequent Elements
  • 692 — Top K Frequent Words
  • 2583 — Kth Largest Sum
  • 3759 — Count Elements With K Greater Values
  • 3974 — Maximum Total Sum

Core Idea

For K largest:

priority_queue<int, vector<int>, greater<int>> pq;

Maintain only K elements.

Recognition

🔑

  • top K
  • kth largest
  • kth smallest
  • most frequent
  • continuously select min/max

Complexity

Usually:

O(n log k)


🟢 19. PREFIX / SUFFIX

Problems

  • 238 — Product of Array Except Self
  • 53 — Maximum Subarray
  • 2270 — Number of Ways to Split Array
  • 3121 — Special Characters II
  • 3818 — Minimum Prefix Removal
  • 3918-type prefix calculations

Core Idea

Precompute information from left/right.

prefix[i]
suffix[i]

Useful when each element needs information from both sides.


🟢 20. INTERVAL / RANGE

Problems

  • 56-type Merge Intervals
  • 57-type Insert Interval
  • 986-type Interval List
  • 1029-type scheduling
  • 1235-type weighted scheduling
  • 2563 — Fair Pairs
  • 2270 — Split Array

Pattern

sort by start
compare current with previous
merge/update

Complexity

O(n log n)


🟢 21. MATRIX

Problems

  • 48 — Rotate Image
  • 54-type Spiral Matrix
  • 64 — Minimum Path Sum
  • 73 — Set Matrix Zeroes
  • 74 — Search a 2D Matrix
  • 1161-type level/grid
  • 1901 — Peak Element II
  • 200 — Number of Islands
  • 2257 — Count Unguarded Cells

Important Patterns

  • Row/column traversal
  • Boundary traversal
  • DFS/BFS
  • Matrix binary search
  • In-place marking

🟢 22. RECURSION

Problems

  • 17
  • 22
  • 39
  • 40
  • 46
  • 47
  • 77
  • 78
  • 90
  • 131
  • 216
  • 491
  • 698
  • 784

Core Formula

function(state):

    if base_case:
        return

    choose
    function(next_state)
    undo

🟢 23. MONOTONIC / ORDER PATTERNS

Problems

  • 739 — Daily Temperatures
  • 503 — Next Greater Element II
  • 556 — Next Greater Element III
  • 2104 — Sum of Subarray Ranges
  • 402 — Remove K Digits
  • 738 — Monotone Increasing Digits
  • 1839 — Longest Beautiful Substring
  • 2414 — Alphabetical Continuous Substring

Recognition

If the question says:

next greater
next smaller
previous greater
previous smaller
monotonic
increasing/decreasing

Think:

🔥 Monotonic Stack


🟢 24. XOR / PREFIX XOR

Problems

  • 136-type Single Number
  • 137 — Single Number II
  • 260 — Single Number III
  • 421 — Maximum XOR
  • 477 — Total Hamming Distance
  • 2044 — Maximum OR
  • 2997 — XOR Equal K
  • 3702 — Non-Zero XOR

Core Rules

a ^ a = 0
a ^ 0 = a
a ^ b = b ^ a

🟢 25. HASHMAP + PREFIX SUM ⭐

This is a very important combined pattern.

Problems

  • 523 — Continuous Subarray Sum
  • 525 — Contiguous Array
  • 560 — Subarray Sum Equals K
  • 974-type Subarrays Divisible by K
  • 1248-type Nice Subarrays

Template

unordered_map<int,int> mp;

mp[0] = 1;

int prefix = 0;

for (int x : nums) {
    prefix += x;

    if (mp.count(prefix - k))
        ans += mp[prefix - k];

    mp[prefix]++;
}

🟢 26. HASHMAP + SLIDING WINDOW ⭐

Problems

  • 3
  • 424
  • 904
  • 1004
  • 1438
  • 1456
  • 2461
  • 2958
  • 3305
  • 3306

Recognition

substring/subarray
+
frequency
+
at most K
+
longest/shortest

→ Sliding Window + HashMap


🟢 27. SORTING + GREEDY ⭐

Problems

  • 846
  • 1296
  • 1338
  • 1481
  • 1679
  • 2244
  • 2491
  • 2563
  • 2517
  • 3974

Recognition

If sorting creates an obvious order of decisions:

sort
→ greedy selection

🟢 28. SORTING + TWO POINTER ⭐

Problems

  • 15 — 3Sum
  • 16 — 3Sum Closest
  • 18 — 4Sum
  • 1679 — K-Sum Pairs
  • 2491 — Divide Players
  • 2563 — Fair Pairs
  • 2517 — Maximum Tastiness

Template

sort(nums.begin(), nums.end());

int left = 0;
int right = nums.size() - 1;

while (left < right) {
    ...
}

🟢 29. DFS / BFS

DFS Problems

  • 200 — Number of Islands
  • 547 — Number of Provinces
  • 102 — Binary Tree Level Order
  • 107 — Level Order II
  • 129 — Sum Root to Leaf
  • 1161 — Maximum Level Sum

BFS Recognition

level
minimum steps
shortest path
nearest
distance

DFS Recognition

connected
explore all
island
component
tree traversal

🟢 30. QUICK PATTERN RECOGNITION 🔥

This is the part I recommend you memorize.

Question saysThink
Pair + sortedTwo Pointer
3Sum / 4SumSort + Two Pointer
Longest substringSliding Window
At most KSliding Window
Exactly KAtMost(K) − AtMost(K−1)
FrequencyHashMap
Subarray Sum KPrefix Sum + HashMap
Sorted arrayBinary Search
Rotated sortedBinary Search
Top KHeap
Next GreaterMonotonic Stack
ParenthesesStack
Generate allBacktracking
All subsetsBacktracking
All permutationsBacktracking
Number of waysDP
Min/Max choicesDP / Greedy
Tree levelBFS
Tree pathDFS
IslandsDFS/BFS
Connected componentsDFS/BFS
XORBit Manipulation
Single NumberXOR
Prime rangeSieve
GCDEuclidean Algorithm
Matrix rotationMatrix/In-place
IntervalsSort + Greedy
Kth largestHeap / Quickselect
Lexicographically smallestGreedy / Stack / Two Pointer depending on problem

⚡ YOUR PERSONAL REVISION ORDER

Based on the problems in your uploaded list, I would revise in this order:

🔥 Level 1 — Must Master

  1. Sliding Window
  2. Two Pointer
  3. HashMap + HashSet
  4. Binary Search
  5. Prefix Sum
  6. Stack / Monotonic Stack
  7. Binary Tree DFS/BFS
  8. Bit Manipulation

🔥 Level 2

  1. Sorting + Greedy
  2. Heap / Priority Queue
  3. Backtracking
  4. Linked List
  5. Matrix
  6. Basic DP

🔥 Level 3

  1. Advanced DP
  2. Graph algorithms
  3. Segment Tree
  4. Advanced Bit Manipulation
  5. Advanced String algorithms

🧠 ONE-LINE MEMORY TRICK

PAIR              → TWO POINTER
WINDOW            → SLIDING WINDOW
FREQUENCY         → HASHMAP
SUBARRAY SUM      → PREFIX SUM
SORTED            → BINARY SEARCH
TOP K             → HEAP
NEXT GREATER      → MONOTONIC STACK
ALL POSSIBILITIES → BACKTRACKING
NUMBER OF WAYS    → DP
TREE LEVEL        → BFS
TREE PATH         → DFS
ISLAND            → DFS/BFS
XOR               → BIT
INTERVAL          → SORT + GREEDY
PRIME             → SIEVE
GCD               → EUCLIDEAN

🟢 1. TWO POINTERS

Core Idea & Variations

  • Opposite Direction: Shrink search space from 0 and n-1 based on target comparison.
  • Same Direction (Fast/Slow): Used for linked list cycle detection, array partitioning, and in-place element removal.

Implementation Template & Edge Cases

// Opposite Direction Template (3Sum Skip Duplicates Example)
sort(nums.begin(), nums.end());
for (int i = 0; i < n - 2; ++i) {
    if (i > 0 && nums[i] == nums[i - 1]) continue; // Skip duplicate anchor
    int left = i + 1, right = n - 1;
    while (left < right) {
        int sum = nums[i] + nums[left] + nums[right];
        if (sum == target) {
            // process result
            while (left < right && nums[left] == nums[left + 1]) left++;  // Skip left dupes
            while (left < right && nums[right] == nums[right - 1]) right--; // Skip right dupes
            left++; right--;
        } else if (sum < target) left++;
        else right--;
    }
}
  • Critical Edge Case: Integer overflow when computing nums[i] + nums[j] + nums[k] in C++. Cast intermediate sums to long long.

🟢 2. VARIABLE SLIDING WINDOW

Core Pattern Enhancement: "Exactly K" Technique

To find subarrays/substrings with Exactly K properties, use the standard pattern formula:


🟢 3. FIXED SIZE SLIDING WINDOW

Standard C++ Template

int left = 0, current_sum = 0, max_ans = 0;
for (int right = 0; right < n; ++right) {
    current_sum += nums[right];
    if (right - left + 1 == k) {
        max_ans = max(max_ans, current_sum);
        current_sum -= nums[left++];
    }
}

🟢 4. HASHMAP / HASHSET & PREFIX COMBINATIONS

Pattern Focus: Prefix Sum + HashMap

Used when querying running totals over arbitrary ranges where .

unordered_map<int, int> prefix_counts;
prefix_counts[0] = 1; // Base case: prefix sum of 0 has occurred once
int current_prefix = 0, count = 0;

for (int num : nums) {
    current_prefix += num;
    if (prefix_counts.count(current_prefix - target)) {
        count += prefix_counts[current_prefix - target];
    }
    prefix_counts[current_prefix]++;
}

Binary Search on Answer Space Framework

Use when searching for the minimum max or maximum min value under constraints:

int low = min_possible, high = max_possible, ans = low;
while (low <= high) {
    int mid = low + (high - low) / 2;
    if (isValid(mid, nums, k)) {
        ans = mid;       // Store valid answer
        low = mid + 1;   // Try to maximize (or high = mid - 1 to minimize)
    } else {
        high = mid - 1;
    }
}

🟢 6. MONOTONIC STACK

Monotonic Stack Cheat Sheet

TargetStack OrderComparison inside while
Next Greater ElementDecreasingst.top() <= current_val
Next Smaller ElementIncreasingst.top() >= current_val
Previous Greater ElementDecreasingst.top() <= current_val
Previous Smaller ElementIncreasingst.top() >= current_val

🟢 7. BIT MANIPULATION

Essential Bit Manipulation Tricks

  • Clear Rightmost Set Bit: n = n & (n - 1)
  • Isolate Rightmost Set Bit: diff = n & (-n)
  • Check if Power of Two: n > 0 && (n & (n - 1)) == 0
  • Toggle Bit at index i: n ^ (1 << i)

🟢 8. QUICK PATTERN RECOGNITION MATRIX

Problem TraitPrimary StrategyCommon Fallback / Alternate
Contiguous Array + Target SumPrefix Sum + MapSliding Window (if non-negative only)
Sorted Array + Pair/Triplet SumTwo PointersBinary Search / Hash Set
Subarray + Min/Max ConstraintsSliding WindowMonotonic Queue
Search Space Bounds KnownBinary Search on AnswerGreedy
Nearest Higher / Lower ElementMonotonic StackSegment Tree
Subsets / All CombinationsBacktrackingBitmask Iteration
K-th Smallest / LargestPriority Queue (Heap)QuickSelect ( avg)
Graph Shortest Path (Unweighted)BFSDFS (unsuitable for shortest path)
Graph Shortest Path (Weighted)Dijkstra's AlgorithmBellman-Ford (if negative edges)

🚀 COMPLETE DSA PATTERN ROADMAP

📌 Master DSA Patterns

#PatternPriority
1Hashing / Frequency Map⭐⭐⭐⭐⭐
2Two Pointers⭐⭐⭐⭐⭐
3Sliding Window⭐⭐⭐⭐⭐
4Prefix Sum⭐⭐⭐⭐⭐
5Difference Array⭐⭐⭐
6Kadane's Algorithm⭐⭐⭐⭐
7Binary Search⭐⭐⭐⭐⭐
8Binary Search on Answer⭐⭐⭐⭐⭐
9Sorting + Greedy⭐⭐⭐⭐⭐
10Fast & Slow Pointers⭐⭐⭐⭐
11Stack⭐⭐⭐⭐⭐
12Monotonic Stack⭐⭐⭐⭐⭐
13Monotonic Queue / Deque⭐⭐⭐⭐
14Heap / Priority Queue⭐⭐⭐⭐⭐
15Top K Elements⭐⭐⭐⭐⭐
16Merge Intervals⭐⭐⭐⭐
17Cyclic Sort⭐⭐⭐⭐
18Linked List Reversal⭐⭐⭐⭐
19Tree DFS⭐⭐⭐⭐⭐
20Tree BFS⭐⭐⭐⭐⭐
21Tree Construction / Recursion⭐⭐⭐⭐
22BST Patterns⭐⭐⭐⭐
23Graph DFS⭐⭐⭐⭐⭐
24Graph BFS⭐⭐⭐⭐⭐
25Multi-Source BFS⭐⭐⭐⭐
26Topological Sort⭐⭐⭐⭐⭐
27Union Find / DSU⭐⭐⭐⭐
28Shortest Path⭐⭐⭐⭐⭐
29Backtracking⭐⭐⭐⭐⭐
301D Dynamic Programming⭐⭐⭐⭐⭐
312D Dynamic Programming⭐⭐⭐⭐⭐
32Knapsack DP⭐⭐⭐⭐⭐
33LCS / String DP⭐⭐⭐⭐
34LIS / Subsequence DP⭐⭐⭐⭐
35Interval DP⭐⭐⭐
36Greedy⭐⭐⭐⭐⭐
37Trie⭐⭐⭐⭐
38Bit Manipulation⭐⭐⭐⭐
39Matrix / Grid⭐⭐⭐⭐⭐
40Divide & Conquer⭐⭐⭐⭐

🔥 SLIDING WINDOW — COMPLETE PATTERN SHEET

Master idea: Expand right → maintain window state → if invalid, move left → update answer/count.

Sliding Window is mainly used for subarrays/substrings, especially problems involving longest, shortest, count, fixed K, at most K, exactly K, at least K, frequencies, or window constraints.

🔗 Sliding Window Patterns — LeetCode

🔗 Complete Sliding Window Pattern Sheet


1️⃣ Fixed Size Window — K

When to Use

Use when the window size is exactly K.

Keywords

  • size K
  • length K
  • every K elements
  • maximum/minimum/average of K
  • substring of length K

C++ Template

int left = 0;
long long sum = 0;

for (int right = 0; right < n; right++) {

    sum += nums[right];

    if (right - left + 1 > k) {
        sum -= nums[left];
        left++;
    }

    if (right - left + 1 == k) {
        // process window
    }
}

Practice Problems

  1. LC 643 — Maximum Average Subarray I
  2. LC 1343 — Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
  3. LC 2461 — Maximum Sum of Distinct Subarrays With Length K
  4. LC 2090 — K Radius Subarray Averages
  5. LC 1456 — Maximum Number of Vowels in a Substring of Given Length
  6. LC 438 — Find All Anagrams in a String
  7. LC 567 — Permutation in String
  8. LC 1052 — Grumpy Bookstore Owner
  9. LC 1423 — Maximum Points You Can Obtain from Cards

🔗 Sliding Window Complete Pattern Sheet


2️⃣ Variable Size — Longest Valid Window

When to Use

Find the longest subarray/substring satisfying a condition.

Template

int left = 0;
int ans = 0;

for (int right = 0; right < n; right++) {

    // add nums[right]

    while (window is invalid) {
        // remove nums[left]
        left++;
    }

    ans = max(ans, right - left + 1);
}

Common Keywords

  • longest substring
  • longest subarray
  • maximum length
  • longest valid window

3️⃣ At Most K

When to Use

The window can contain at most K occurrences/distinct elements/violations.

Template

int left = 0;
int ans = 0;

for (int right = 0; right < n; right++) {

    // add nums[right]

    while (condition > k) {
        // remove nums[left]
        left++;
    }

    ans = max(ans, right - left + 1);
}

Examples

  • At most K distinct characters
  • At most K zeros
  • At most K odd numbers
  • At most K different values

4️⃣ At Least K / Minimum Window

When to Use

Find the smallest window satisfying a condition.

Template

int left = 0;
int ans = INT_MAX;

for (int right = 0; right < n; right++) {

    // add nums[right]

    while (window is valid) {

        ans = min(ans, right - left + 1);

        // remove nums[left]
        left++;
    }
}

Keywords

  • minimum length
  • shortest substring
  • smallest window
  • minimum window

5️⃣ Exactly K

When to Use

When the problem asks for exactly K distinct elements, odd numbers, zeros, etc.

Main Trick

Exactly(K) = AtMost(K) - AtMost(K - 1)

Template

long long exactlyK(vector<int>& nums, int k) {
    return atMost(nums, k) - atMost(nums, k - 1);
}

6️⃣ Count All Valid Subarrays

When to Use

The question asks:

  • How many subarrays?
  • Count subarrays satisfying condition
  • Number of substrings

Key Formula

When the current window [left ... right] is valid:

count += right - left + 1;

Template

long long ans = 0;
int left = 0;

for (int right = 0; right < n; right++) {

    // add nums[right]

    while (window is invalid) {
        // remove nums[left]
        left++;
    }

    ans += right - left + 1;
}

7️⃣ Frequency Map Window

When to Use

Use when the condition depends on frequency/count of characters or values.

Template

unordered_map<char, int> freq;

int left = 0;

for (int right = 0; right < n; right++) {

    freq[s[right]]++;

    while (/* invalid frequency condition */) {
        freq[s[left]]--;

        if (freq[s[left]] == 0)
            freq.erase(s[left]);

        left++;
    }

    // process window
}

8️⃣ Distinct Elements

When to Use

Problems involving:

  • unique elements
  • distinct characters
  • no duplicate
  • K distinct values

Template

unordered_map<int, int> freq;

int left = 0;

for (int right = 0; right < n; right++) {

    freq[nums[right]]++;

    while (freq.size() > k) {
        freq[nums[left]]--;

        if (freq[nums[left]] == 0)
            freq.erase(nums[left]);

        left++;
    }

    // valid window
}

9️⃣ No Repeating Characters

When to Use

Find the longest substring with unique characters.

Template

unordered_map<char, int> freq;

int left = 0;
int ans = 0;

for (int right = 0; right < s.size(); right++) {

    freq[s[right]]++;

    while (freq[s[right]] > 1) {
        freq[s[left]]--;
        left++;
    }

    ans = max(ans, right - left + 1);
}

🔟 Character Replacement / Limited Changes

When to Use

When you can modify/replace at most K elements.

Typical condition:

window size - most frequent element <= K

Template

unordered_map<char, int> freq;

int left = 0;
int maxFreq = 0;
int ans = 0;

for (int right = 0; right < s.size(); right++) {

    freq[s[right]]++;

    maxFreq = max(maxFreq, freq[s[right]]);

    while ((right - left + 1) - maxFreq > k) {
        freq[s[left]]--;
        left++;
    }

    ans = max(ans, right - left + 1);
}

1️⃣1️⃣ Binary Array Sliding Window

When to Use

Useful for arrays containing:

0 / 1

Especially:

  • K zeros
  • K ones
  • longest sequence
  • flips
  • consecutive elements

Example Condition

while (zeros > k) {
    if (nums[left] == 0)
        zeros--;

    left++;
}

1️⃣2️⃣ Sliding Window + Set / HashSet

When to Use

Use a set or unordered_set when you only care about presence/uniqueness, rather than exact frequency.

Template

unordered_set<int> st;

int left = 0;

for (int right = 0; right < n; right++) {

    while (st.count(nums[right])) {
        st.erase(nums[left]);
        left++;
    }

    st.insert(nums[right]);

    // process window
}

1️⃣3️⃣ Sliding Window + Deque

When to Use

Use when you need the maximum/minimum element of the current window efficiently.

Typical problems:

  • Sliding Window Maximum
  • Sliding Window Minimum
  • Maintain max/min while window moves

Template

deque<int> dq;

for (int right = 0; right < n; right++) {

    while (!dq.empty() && nums[dq.back()] <= nums[right])
        dq.pop_back();

    dq.push_back(right);

    if (dq.front() <= right - k)
        dq.pop_front();

    if (right >= k - 1) {
        // nums[dq.front()] = maximum
    }
}

1️⃣4️⃣ Two Sliding Windows

When to Use

Useful when you need to compare two constraints or calculate:

Exactly K
At Most K
At Least K

Most important relationship:

Exactly K = AtMost(K) - AtMost(K - 1)

This pattern appears frequently in counting subarray problems.


1️⃣5️⃣ Sliding Window + Advanced State

When to Use

Use when maintaining the window requires additional information such as:

  • frequency maps
  • prime factors
  • character counts
  • number of violations
  • sum
  • product
  • bitmask
  • sets
  • deque
  • multiple conditions

General Template

int left = 0;

for (int right = 0; right < n; right++) {

    // 1. Add right element
    add(nums[right]);

    // 2. Fix invalid window
    while (invalid()) {
        remove(nums[left]);
        left++;
    }

    // 3. Update answer
    updateAnswer(left, right);
}

🧠 SLIDING WINDOW DECISION TREE

Is it a contiguous subarray / substring?
            |
           YES
            |
     Is window size fixed?
       /             \
     YES              NO
      |                |
   Fixed K       Is it longest?
                    /      \
                  YES       NO
                   |         |
             Keep valid   Is it minimum?
             window          /     \
                           YES      NO
                            |         |
                       Shrink while   Count?
                       valid          |
                                      YES
                                       |
                              AtMost / Exactly

⚡ 10-SECOND INTERVIEW CHECKLIST

Before coding, ask:

1. Is it contiguous?
2. Is the window fixed or variable?
3. What makes the window invalid?
4. What state must I maintain?
5. When should left move?
6. Am I finding longest?
7. Am I finding shortest?
8. Am I counting?
9. Is it At Most K?
10. Can Exactly K = AtMost(K) - AtMost(K-1)?

📚 USEFUL LEETCODE REFERENCES

🔗 Sliding Window Patterns

🔗 Complete Sliding Window Revision

🔗 Sliding Window Complete Pattern Sheet

🔗 DSA All Pattern-Wise Master Sheet

🔗 C++ STL Containers Cheat Sheet

🔗 50+ Useful C++ Functions

Comments (31)