> ## Documentation Index
> Fetch the complete documentation index at: https://resources.devweekends.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Pattern Recognition

> Learn to instantly recognize common problem patterns and select the right algorithm

export const Icon = ({icon}) => {
  const iconMap = {
    'calendar-check': '📅',
    'sun': '☀️',
    'stopwatch': '⏱️',
    'clock': '🕐',
    'bug': '🐛',
    'heart-pulse': '💓',
    'moon': '🌙',
    'trophy': '🏆',
    'chart-line': '📈',
    'list-check': '✅',
    'book': '📖',
    'brain': '🧠',
    'pencil': '✏️',
    'database': '🗄️',
    'chart-pie': '📊',
    'shield': '🛡️',
    'clipboard': '📋',
    'bolt': '⚡',
    'graduation-cap': '🎓',
    'eye': '👁️',
    'ruler': '📏',
    'search': '🔍',
    'wand-magic-sparkles': '✨',
    'diagram-project': '📐',
    'sitemap': '🗺️',
    'dumbbell': '🏋️',
    'toolbox': '🧰',
    'calculator': '🔢',
    'list-ol': '📝',
    'magnifying-glass': '🔍',
    'tree': '🌳',
    'table': '📊',
    'layer-group': '📚',
    'shuffle': '🔀'
  };
  return <span>{iconMap[icon] || '📌'}</span>;
};

# <Icon icon="eye" /> Pattern Recognition

The fastest competitive programmers don't think harder—they **recognize patterns faster**. This chapter trains your pattern recognition to instantly spot which technique to apply.

<img src="https://mintcdn.com/devweeekends/AEOaWh79Ur7CdHHv/images/courses/cp/pattern-recognition.svg?fit=max&auto=format&n=AEOaWh79Ur7CdHHv&q=85&s=673e145fb84ed8e4ad2ef8469fbcb3a4" alt="Pattern Recognition Flow" width="700" height="250" data-path="images/courses/cp/pattern-recognition.svg" />

***

## <Icon icon="brain" /> The Recognition Framework

<Warning>
  **The Secret:** After solving 500+ problems, you stop "solving" and start "recognizing." This chapter gives you shortcuts to that recognition.
</Warning>

### The 3-Step Recognition Process

<img src="https://mintcdn.com/devweeekends/AEOaWh79Ur7CdHHv/images/courses/cp/recognition-process.svg?fit=max&auto=format&n=AEOaWh79Ur7CdHHv&q=85&s=eb510ea9847adf4add23ba54b30a1d24" alt="3-Step Recognition" width="650" height="220" data-path="images/courses/cp/recognition-process.svg" />

<Steps>
  <Step title="Read the Constraint">
    The constraint is the FIRST clue to the algorithm.
  </Step>

  <Step title="Identify the Question Type">
    What are they asking? Count, optimize, find, check?
  </Step>

  <Step title="Match the Pattern">
    Combine constraint + question type = algorithm pattern.
  </Step>
</Steps>

***

## <Icon icon="ruler" /> Constraint → Algorithm Map

### The Golden Table

<img src="https://mintcdn.com/devweeekends/AEOaWh79Ur7CdHHv/images/courses/cp/constraint-algo-map.svg?fit=max&auto=format&n=AEOaWh79Ur7CdHHv&q=85&s=ba8740c8ecb96332b9d4036549985e26" alt="Constraint to Algorithm Map" width="1080" height="1080" data-path="images/courses/cp/constraint-algo-map.svg" />

| Constraint (n) | Max Operations   | Likely Algorithm                        |
| -------------- | ---------------- | --------------------------------------- |
| n ≤ 10         | 10! = 3.6M       | Brute force, permutations, backtracking |
| n ≤ 20         | 2²⁰ = 1M         | Bitmask DP, subset enumeration          |
| n ≤ 100        | n³ = 1M          | Floyd-Warshall, O(n³) DP                |
| n ≤ 500        | n³ = 125M        | O(n²) with optimization                 |
| n ≤ 5,000      | n² = 25M         | O(n²) DP, all pairs                     |
| n ≤ 10⁵        | n log n          | Sorting, binary search, segment tree    |
| n ≤ 10⁶        | O(n)             | Linear scan, two pointers, prefix sum   |
| n ≤ 10⁹        | O(log n)         | Binary search, math formula             |
| n ≤ 10¹⁸       | O(1) or O(log n) | Math formula, matrix exponentiation     |

***

## <Icon icon="search" /> Question Type Patterns

### Pattern 1: "Count the number of..."

<CardGroup cols={2}>
  <Card title="Count subarrays with property" icon="calculator">
    **Technique:** Prefix sum + hashmap

    ```cpp theme={null}
    // "Count subarrays with sum = k"
    map<int, int> prefix_count;
    prefix_count[0] = 1;
    int sum = 0, count = 0;
    for (int x : arr) {
        sum += x;
        count += prefix_count[sum - k];
        prefix_count[sum]++;
    }
    ```
  </Card>

  <Card title="Count subsequences with property" icon="layer-group">
    **Technique:** DP (usually 1D or 2D)

    ```cpp theme={null}
    // "Count increasing subsequences of length k"
    // dp[i][j] = count ending at i, length j
    for (int i = 0; i < n; i++) {
        dp[i][1] = 1;
        for (int j = 0; j < i; j++) {
            if (a[j] < a[i]) {
                for (int k = 2; k <= K; k++) {
                    dp[i][k] += dp[j][k-1];
                }
            }
        }
    }
    ```
  </Card>
</CardGroup>

### Pattern 2: "Find the maximum/minimum..."

<img src="https://mintcdn.com/devweeekends/AEOaWh79Ur7CdHHv/images/courses/cp/optimize-pattern.svg?fit=max&auto=format&n=AEOaWh79Ur7CdHHv&q=85&s=0d5ede613a254bc275eec891784c0d3d" alt="Optimization Patterns" width="650" height="220" data-path="images/courses/cp/optimize-pattern.svg" />

| What to Optimize | First Try           | If TLE, Try             |
| ---------------- | ------------------- | ----------------------- |
| Max sum subarray | Kadane's O(n)       | Already optimal         |
| Min cost path    | Dijkstra O(E log V) | 0-1 BFS if weights 0/1  |
| Max flow         | Ford-Fulkerson      | Dinic's algorithm       |
| Max matching     | Hungarian O(n³)     | Hopcroft-Karp O(E√V)    |
| Min operations   | BFS                 | Binary search on answer |

### Pattern 3: "Check if possible..."

<CardGroup cols={2}>
  <Card title="Can we achieve X?" icon="check">
    **Technique:** Binary search on answer

    ```cpp theme={null}
    // "Can we split array into k parts 
    // with max sum ≤ mid?"
    int lo = max_element, hi = total_sum;
    while (lo < hi) {
        int mid = (lo + hi) / 2;
        if (canSplit(arr, k, mid)) {
            hi = mid;
        } else {
            lo = mid + 1;
        }
    }
    return lo;
    ```
  </Card>

  <Card title="Does path/assignment exist?" icon="route">
    **Technique:** DFS/BFS or DP

    ```cpp theme={null}
    // "Can we reach target?"
    bool dfs(int node, int target, 
             vector<bool>& visited) {
        if (node == target) return true;
        visited[node] = true;
        for (int next : adj[node]) {
            if (!visited[next] && 
                dfs(next, target, visited)) {
                return true;
            }
        }
        return false;
    }
    ```
  </Card>
</CardGroup>

### Pattern 4: "Find the kth..."

| Problem Type                  | Algorithm                  | Complexity       |
| ----------------------------- | -------------------------- | ---------------- |
| Kth smallest in array         | nth\_element / quickselect | O(n)             |
| Kth smallest in sorted arrays | Binary search              | O(log(min(m,n))) |
| Kth smallest in BST           | In-order traversal         | O(k)             |
| Kth smallest sum              | Priority queue             | O(k log k)       |

***

## <Icon icon="wand-magic-sparkles" /> Keyword → Algorithm Triggers

<img src="https://mintcdn.com/devweeekends/AEOaWh79Ur7CdHHv/images/courses/cp/keyword-triggers.svg?fit=max&auto=format&n=AEOaWh79Ur7CdHHv&q=85&s=dc774416788fd9d67beff840a91454ea" alt="Keyword Triggers" width="700" height="280" data-path="images/courses/cp/keyword-triggers.svg" />

### Instant Recognition Keywords

| Keyword in Problem           | Algorithm to Consider                 |
| ---------------------------- | ------------------------------------- |
| "subarray sum"               | Prefix sum, sliding window, kadane    |
| "longest increasing"         | DP, binary search + DP                |
| "shortest path"              | BFS (unweighted), Dijkstra (weighted) |
| "number of ways"             | DP, combinatorics                     |
| "partition into k"           | Binary search on answer               |
| "lexicographically smallest" | Greedy, trie                          |
| "connected components"       | DFS, DSU                              |
| "minimum spanning tree"      | Kruskal, Prim                         |
| "all pairs"                  | Floyd-Warshall, n × Dijkstra          |
| "parentheses/brackets"       | Stack                                 |
| "intervals/meetings"         | Sort by end, greedy                   |
| "palindrome"                 | Two pointers, DP, Manacher            |
| "permutation"                | Factorial, backtracking               |
| "subset"                     | Bitmask, DP                           |
| "modulo 10^9+7"              | DP (count), use mod everywhere        |

***

## <Icon icon="diagram-project" /> Visual Pattern Gallery

### Array Patterns

<img src="https://mintcdn.com/devweeekends/AEOaWh79Ur7CdHHv/images/courses/cp/array-patterns.svg?fit=max&auto=format&n=AEOaWh79Ur7CdHHv&q=85&s=73342ab84aded3c3441aa4be6a3c18a2" alt="Array Pattern Recognition" width="700" height="250" data-path="images/courses/cp/array-patterns.svg" />

```
PATTERN: Contiguous subarray with property
SIGNALS: "subarray", "contiguous", "consecutive"
TECHNIQUES: 
  - Prefix sum (sum queries)
  - Sliding window (fixed or variable size)
  - Two pointers (sorted or special property)
  - Monotonic deque (min/max in window)

PATTERN: Find elements with relationship
SIGNALS: "pair", "triplet", "two numbers that"
TECHNIQUES:
  - Sort + two pointers
  - Hashmap for complement
  - Binary search after sorting
```

### Tree Patterns

```
PATTERN: Path queries on tree
SIGNALS: "path between nodes", "distance", "LCA"
TECHNIQUES:
  - DFS for simple paths
  - Binary lifting for LCA
  - HLD for path updates

PATTERN: Subtree queries
SIGNALS: "sum in subtree", "count in subtree"
TECHNIQUES:
  - DFS in/out times
  - Euler tour + range queries
```

### Graph Patterns

```
PATTERN: Shortest path
SIGNALS: "minimum distance", "fewest steps"
TECHNIQUES:
  - BFS (unweighted)
  - Dijkstra (positive weights)
  - Bellman-Ford (negative weights)
  - 0-1 BFS (weights 0 or 1)

PATTERN: Cycle detection
SIGNALS: "cycle", "loop", "circular dependency"
TECHNIQUES:
  - DFS with colors (directed)
  - Union-Find (undirected)
  - Check if edges ≥ vertices in component
```

***

## <Icon icon="sitemap" /> Decision Trees for Common Problems

### "Given an array..." Decision Tree

<img src="https://mintcdn.com/devweeekends/AEOaWh79Ur7CdHHv/images/courses/cp/array-decision-tree.svg?fit=max&auto=format&n=AEOaWh79Ur7CdHHv&q=85&s=0bc3206f5690549b1a8771af8e520c05" alt="Array Problem Decision Tree" width="700" height="320" data-path="images/courses/cp/array-decision-tree.svg" />

```
Q: What are you asked to find?
├── Sum/XOR of subarray?
│   ├── Single query → Prefix sum/XOR
│   └── Multiple queries → Prefix sum array
│
├── Maximum/Minimum in range?
│   ├── Static array → Sparse table
│   └── Updates allowed → Segment tree
│
├── Longest subarray with property?
│   ├── Two-pointer property → Two pointers
│   └── Complex property → DP
│
├── Number of subarrays with property?
│   ├── Sum = k → Hashmap + prefix sum
│   ├── Fixed length → Sliding window
│   └── Other → DP or combinatorics
│
└── Reorder/partition array?
    ├── Minimize max → Binary search on answer
    └── Specific order → Greedy or DP
```

### "Given a string..." Decision Tree

```
Q: What are you asked to find?
├── Substring matching?
│   ├── Single pattern → KMP, Z-algorithm
│   └── Multiple patterns → Aho-Corasick, trie
│
├── Palindrome questions?
│   ├── Check palindrome → Two pointers
│   ├── Longest palindrome → DP, Manacher
│   └── Count palindromes → DP
│
├── Lexicographically smallest/largest?
│   ├── By deletion → Stack-based greedy
│   └── By rearrangement → Sort characters
│
└── Edit distance/similarity?
    └── DP (LCS, edit distance)
```

***

## <Icon icon="dumbbell" /> Pattern Recognition Drills

### Drill 1: Speed Classification

Read each problem description and identify the pattern in under 10 seconds:

<Accordion title="Problem Set (Click to expand)">
  **P1:** "Given an array of n integers, find the number of pairs (i,j) where i \< j and a\[i] + a\[j] = k."

  * **Pattern:** Two Sum → Hashmap

  **P2:** "Given a binary tree, find the maximum path sum from any node to any node."

  * **Pattern:** Tree DP → DFS with return value

  **P3:** "Given n intervals, find the minimum number of points such that each interval contains at least one point."

  * **Pattern:** Interval covering → Sort by end + greedy

  **P4:** "Given a string, find the longest palindromic substring."

  * **Pattern:** Palindrome → DP or expand from center

  **P5:** "Given a weighted graph, find if negative cycle exists."

  * **Pattern:** Negative cycle → Bellman-Ford

  **P6:** "Given array, answer queries for minimum in range \[l,r]."

  * **Pattern:** Range min query → Sparse table or segment tree

  **P7:** "Given n items with weight and value, maximize value with capacity W."

  * **Pattern:** 0/1 Knapsack → 2D DP

  **P8:** "Given a sequence, count inversions (pairs where i \< j but a\[i] > a\[j])."

  * **Pattern:** Inversions → Merge sort or BIT
</Accordion>

### Drill 2: Constraint → Algorithm

| Constraint                      | Your Answer |
| ------------------------------- | ----------- |
| n ≤ 15                          | ?           |
| n ≤ 1000, find shortest path    | ?           |
| n ≤ 10⁵, range sum queries      | ?           |
| n ≤ 10⁶, single pass required   | ?           |
| n ≤ 10¹⁸, compute nth Fibonacci | ?           |

<Accordion title="Answers">
  | Constraint                      | Algorithm                            |
  | ------------------------------- | ------------------------------------ |
  | n ≤ 15                          | Bitmask DP, brute force              |
  | n ≤ 1000, find shortest path    | Floyd-Warshall O(n³) or BFS/Dijkstra |
  | n ≤ 10⁵, range sum queries      | Prefix sum or Segment tree           |
  | n ≤ 10⁶, single pass required   | O(n) linear scan, two pointers       |
  | n ≤ 10¹⁸, compute nth Fibonacci | Matrix exponentiation                |
</Accordion>

***

## <Icon icon="bolt" /> Quick Reference Cheat Sheet

### One-Liner Pattern Recognition

```
Array + Sum → Prefix Sum
Array + Sorted + Target → Two Pointers / Binary Search
Array + Window Property → Sliding Window
Array + Subsequence → DP

String + Match → KMP / Hashing
String + Palindrome → DP / Manacher
String + Lexicographic → Greedy / Trie

Graph + Shortest → BFS (unweighted) / Dijkstra (weighted)
Graph + Connectivity → DFS / DSU
Graph + Minimum cost → MST (Kruskal/Prim)
Graph + Flow → Ford-Fulkerson / Dinic

Tree + Path → DFS
Tree + LCA → Binary Lifting
Tree + Subtree → Euler Tour

"Number of ways" → DP + mod
"Minimum steps" → BFS
"Is it possible" → Binary Search on Answer
"Maximum subset" → DP / Greedy
```

***

<Tip>
  **Pattern recognition is a skill that develops with practice.**

  Every problem you solve adds to your pattern library. After 500 problems, you'll look at a new problem and think "Oh, this is just \[pattern] with a twist."

  **Keep solving. Keep recognizing. Keep winning!** 🏆
</Tip>
