Skip to main content

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.

The Mistake Journal System

Every wrong answer contains a lesson. Most competitive programmers make the same mistakes repeatedly because they don’t track them. This chapter gives you a systematic approach to eliminate recurring errors and accelerate your improvement. Mistake Learning Cycle

Why Mistakes Repeat

The brutal truth: Without tracking, you will make the same mistake 10+ times before it sticks. With tracking, you can reduce that to 2-3 times.

The Memory Problem

// Week 1: You get WA due to integer overflow
// You fix it and move on

// Week 3: You forget about integer overflow
// You get WA again, spend 30 minutes debugging

// Week 5: Same mistake, same frustration
// You feel like you're not improving

// THE FIX: Write it down. Review it. Never forget.

The 5 Categories of CP Mistakes

5 Categories of Mistakes
CategoryDescriptionExample
SyntaxLanguage/compiler errorsForgetting semicolon, wrong brackets
LogicAlgorithm is fundamentally wrongWrong recurrence relation
ImplementationRight idea, wrong codeOff-by-one, wrong index
Edge CasesWorks for most, fails for extremesn=0, n=1, empty string
CarelessSilly mistakes under pressureWrong variable name, copy-paste error

Setting Up Your Mistake Journal

Option 1: Notion Template

## Mistake Entry #[number]

**Date:** YYYY-MM-DD
**Problem:** [Problem Name + Link]
**Mistake Category:** [Syntax / Logic / Implementation / Edge Case / Careless]

### What Happened
[Describe the mistake in 1-2 sentences]

### The Code That Was Wrong
```cpp
// Paste the buggy code here

The Correct Code

// Paste the fixed code here

Root Cause Analysis

  • Why did I make this mistake?
  • What was I thinking when I wrote it?
  • What should I have done differently?

Prevention Strategy

  • How will I catch this next time?
  • What mental check should I add?
  • Any template/snippet to prevent this?

Tags

#overflow #off-by-one #edge-case #modulo #binary-search

### Option 2: Simple Spreadsheet

| Date | Problem | Category | Mistake | Fix | Prevention | Tags |
|------|---------|----------|---------|-----|------------|------|
| 2024-01-15 | CF 1234A | Overflow | Used int for n*n | Cast to ll | Always ll for products | #overflow |
| 2024-01-16 | CF 1235B | Edge | Empty string | Check s.empty() | Test n=0 first | #edge #string |

### Option 3: VS Code Snippets

Create a snippets file that grows from your mistakes:

```json
{
  "Safe Modular Add": {
    "prefix": "modadd",
    "body": [
      "((${1:a} % MOD) + (${2:b} % MOD) + MOD) % MOD"
    ],
    "description": "Mistake #14: Negative mod issue"
  },
  "Binary Search Template": {
    "prefix": "binsearch",
    "body": [
      "int lo = 0, hi = n - 1;",
      "while (lo < hi) {",
      "    int mid = lo + (hi - lo) / 2;",
      "    if (${1:condition}) hi = mid;",
      "    else lo = mid + 1;",
      "}",
      "// Answer is at index lo"
    ],
    "description": "Mistake #23: Binary search off-by-one"
  }
}

The Master Mistake Database

Top 50 Common CP Mistakes

Build your own database. Here’s a starter:

Integer Overflow (THE #1 KILLER)

// MISTAKE: Using int for large products
int n = 1e5;
int result = n * n;  // OVERFLOW! 

// FIX: Always use long long for products
long long result = (long long)n * n;  // Correct

Off-By-One Errors

// MISTAKE: Wrong loop bounds
for (int i = 0; i <= n; i++) {
    arr[i] = 0;  // Access arr[n] - out of bounds!
}

// FIX: Use < n for 0-indexed arrays
for (int i = 0; i < n; i++) {
    arr[i] = 0;
}

Modular Arithmetic Pitfalls

// MISTAKE: Negative numbers in modulo
int x = -5 % 3;  // Result is -2 in C++!

// FIX: Safe modulo
int safe_mod(int x, int m) {
    return ((x % m) + m) % m;
}

Binary Search Edge Cases

// MISTAKE: Infinite loop
while (lo <= hi) {
    int mid = (lo + hi) / 2;  // Can overflow!
    if (arr[mid] < target) lo = mid;  // INFINITE LOOP!
}

// FIX: Correct binary search
while (lo < hi) {
    int mid = lo + (hi - lo) / 2;  // Safe from overflow
    if (arr[mid] < target) lo = mid + 1;
    else hi = mid;
}

Graph Algorithm Mistakes

// MISTAKE: Not resetting visited array between test cases
bool visited[N];

void solve() {
    // visited still has values from previous test!
}

// FIX: Reset at start of each test case
void solve() {
    memset(visited, false, sizeof(visited));
    // or
    fill(visited, visited + n, false);
}

String Processing Errors

// MISTAKE: Using cin >> s for strings with spaces
string s;
cin >> s;  // Only reads until first space!

// FIX: Use getline for full line
getline(cin, s);

// WATCH OUT: After cin >> n, you need cin.ignore()
int n; cin >> n;
cin.ignore();
getline(cin, s);

Array Initialization

// MISTAKE: Assuming global arrays are initialized
int dp[N][M];  // Local: RANDOM values!

// FIX: Always initialize
int dp[N][M] = {};  // All zeros

// or
memset(dp, 0, sizeof(dp));
memset(dp, -1, sizeof(dp));  // Works for -1 and 0 only!

// For other values, use fill
fill(&dp[0][0], &dp[0][0] + N*M, INF);

Analyzing Your Mistakes

Weekly Mistake Review

Every Sunday, review your mistake journal: Mistake Analysis Process
1

Count by Category

How many of each type did you make this week?
  • Overflow: 3
  • Edge cases: 5
  • Logic: 2
Focus next week on edge cases!
2

Identify Patterns

Are certain topics causing more mistakes?
  • Binary search: 4 mistakes
  • DP: 1 mistake
Study binary search more!
3

Check for Repeats

Did you make any mistake you’ve made before?
  • Integer overflow: Made it twice this week!
Add reminder to pre-coding checklist!
4

Update Your Checklist

Add the most common mistakes to your pre-submit checklist.
Monthly Mistake Trends Track these metrics monthly:
  • Total mistakes per week (should decrease)
  • Repeat mistakes (should decrease faster)
  • Time to debug (should decrease)
  • New mistake types (sign of tackling harder problems)

The Prevention System

Pre-Coding Checklist

Before you start coding ANY problem, ask:
☐ Does this problem involve large numbers? → Use long long
☐ Am I working with arrays? → Double-check bounds
☐ Is there modular arithmetic? → Use safe_mod function
☐ Multiple test cases? → Reset all global variables
☐ String input after integers? → cin.ignore() before getline
☐ Binary search needed? → Use tested template

Pre-Submit Checklist

Before hitting submit, verify:
☐ All variables use correct data types
☐ Array indices are within bounds
☐ Edge cases handled (n=0, n=1, empty input)
☐ Output format matches exactly (spaces, newlines)
☐ All test cases produce correct output
☐ No debug statements left in code (cerr, cout)

The “5 Second Rule”

Before submitting, pause for 5 seconds and scan for:
  1. Data types (int vs long long)
  2. Loop bounds (< vs <=)
  3. Edge cases (n=0, n=1)
  4. Output format (newlines, spaces)
  5. Debug output (remove cerr/cout debugging)

Mistake Templates by Topic

Binary Search Mistakes

// Template: Safe binary search (lower bound)
int binary_search_lower(vector<int>& arr, int target) {
    int lo = 0, hi = arr.size();  // hi = size, not size-1
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;  // Prevent overflow
        if (arr[mid] < target) lo = mid + 1;
        else hi = mid;
    }
    return lo;  // First element >= target
}

// Common mistake: Using <= in while condition with this template
// Common mistake: Using (lo + hi) / 2 → can overflow
// Common mistake: lo = mid instead of lo = mid + 1 → infinite loop

DP Mistakes

// Template: Safe DP initialization
const long long INF = 1e18;  // Not INT_MAX (adding to it overflows)
vector<vector<long long>> dp(n + 1, vector<long long>(m + 1, INF));

// Common mistakes:
// 1. Using INT_MAX → addition causes overflow
// 2. Wrong dimension order
// 3. Not handling base cases
// 4. Wrong recurrence order (depends on what values)

Graph Mistakes

// Template: Safe BFS
void bfs(int start) {
    queue<int> q;
    vector<bool> visited(n + 1, false);  // Always declare locally!
    
    q.push(start);
    visited[start] = true;  // Mark BEFORE pushing
    
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        
        for (int v : adj[u]) {
            if (!visited[v]) {
                visited[v] = true;  // Mark BEFORE pushing
                q.push(v);
            }
        }
    }
}

// Common mistakes:
// 1. Marking visited AFTER pushing → duplicates in queue
// 2. Not resetting visited between test cases
// 3. Wrong graph size (1-indexed vs 0-indexed)

Quick Reference: The Mistake Lookup Table

When you get WA or TLE, check this table:
SymptomLikely CauseQuick Fix
Wrong Answer on large inputInteger overflowCast to long long
Wrong Answer on sampleLogic errorRe-read problem, trace by hand
Wrong Answer test 2Edge case (n=1)Add special case handling
Time Limit ExceededAlgorithm too slowOptimize or change approach
TLE with O(n²)Need O(n log n)Use sorting/binary search/map
Runtime ErrorArray out of boundsCheck all array accesses
Runtime ErrorStack overflowConvert recursion to iteration
Wrong Answer random testsOff-by-one errorCheck loop bounds carefully
Works locally, fails onlineUninitialized variablesInitialize everything

Building Mistake Immunity

The 3-Strike Rule

If you make the same mistake 3 times:
  1. Create a snippet to prevent it
  2. Add it to pre-submit checklist
  3. Teach it to someone else (explaining cements memory)

The Mistake Flashcard System

Create flashcards for your top mistakes:
FRONT: Integer overflow in multiplication
BACK: Always cast at least one operand to long long
       (long long)a * b NOT (long long)(a * b)
Review flashcards weekly before contests.

The “Never Again” List

Keep a pinned list of your top 5 most frustrating mistakes:
MY "NEVER AGAIN" LIST:

1. Integer overflow in n*n → ALWAYS use long long
2. Forgot to reset visited[] → Reset at start of solve()
3. Wrong binary search termination → Use tested template
4. Modulo with negative numbers → Use safe_mod()
5. Reading string after int → Always cin.ignore()
Read this before every contest.
Your mistakes are your competitive advantage.Most people make mistakes and forget them. If you track, analyze, and systematically eliminate your mistakes, you’ll improve faster than 90% of competitors.Start your mistake journal TODAY.

Interview Deep-Dive

Strong Answer:
  • The systemic fix has three layers: prevention, detection, and verification. Prevention: add #define int long long to my contest template, or at minimum use long long for any variable that participates in multiplication or accumulation. Detection: compile with -fsanitize=undefined during local testing, which flags signed overflow at runtime. Verification: add an explicit item to my pre-submit checklist — “scan every multiplication and sum for overflow potential.”
  • To measure effectiveness, I continue logging mistakes for the next month and compare the overflow WA rate. If it drops from 40% to under 10%, the fix is working. If it persists, the fix is not addressing the root cause — perhaps the overflows are happening in less obvious places like implicit int-to-int multiplication inside STL operations.
  • Beyond the immediate fix, I would audit my past overflow bugs and categorize them: (1) product of two ints, (2) running sum exceeding 2 times 10^9, (3) modular arithmetic intermediate values, (4) array size calculations. Each subcategory might need a different prevention strategy.
Follow-up: Is there a tradeoff to always using long long everywhere, even when int would suffice?Yes. Long long doubles memory usage for every integer variable and array. A segment tree with 4 million nodes goes from 16 MB to 32 MB. On problems with 256 MB memory limits and large data structures, this can cause MLE. Long long also has slightly slower arithmetic on some architectures (though this is negligible on modern 64-bit CPUs). In practice, the time saved from never debugging overflow bugs far outweighs these costs in 99% of contest problems.
Strong Answer:
  • The 3-strike rule: if I make the same mistake three times (identified via my mistake journal tags), I escalate to a permanent fix. The first occurrence is a learning moment. The second is a warning. The third means my normal coding habits will not prevent this — I need a structural intervention.
  • Structural interventions, ranked by effectiveness: (1) A code snippet in my IDE that auto-generates the correct pattern. For example, after my third binary search infinite loop, I created a VS Code snippet binsearch that expands to a tested template with lo + (hi - lo) / 2 and lo < hi. Now I never hand-write binary search bounds. (2) A checklist item I review before every submission. (3) A macro in my template that handles the case automatically (like safe modular arithmetic).
  • The snippet approach works because it removes the human from the error-prone step. I do not trust myself to remember lo + (hi - lo) / 2 under contest pressure — I trust the snippet that I tested once and reuse forever. This is the same principle as using library functions instead of hand-rolled implementations.
  • Measurement: after implementing snippets for my top 5 recurring bugs, my first-submission acceptance rate increased from 55% to 75% over 2 months. Each prevented WA saves 5-15 minutes of debugging, which compounds across a contest to an extra problem solved.
Follow-up: How do you decide between a snippet, a checklist item, and a template macro?Snippets for patterns with complex syntax that I frequently get wrong (binary search, segment tree, modular inverse). Checklist items for conceptual checks that cannot be automated (did I handle the n=1 edge case? did I reset globals between test cases?). Template macros for things that should always be true in every solution (fast I/O, long long types, safe mod function). The principle: automate what can be automated, checklist what cannot, and template what is universal.
Strong Answer:
  • The forgetting curve (Ebbinghaus, 1885) shows humans forget approximately 50% of new information within 24 hours and 70% within a week without deliberate review. A mistake made on Saturday is largely forgotten by the following Saturday’s contest. The journal is the review mechanism that prevents this decay.
  • Concrete evidence from my own practice: before journaling, I made the integer overflow mistake an average of once per contest for 3 months (12 occurrences). After starting a journal and reviewing it weekly, the same mistake dropped to once per month within 6 weeks. That is a 75% reduction, translating to roughly 10 minutes saved per contest.
  • The journal also reveals patterns invisible to unaided memory. You think you struggle with DP, but your journal shows 80% of your DP mistakes are specifically in the base case initialization, not in the recurrence relation. That level of specificity transforms vague “practice more DP” into actionable “drill DP base cases.”
  • The opportunity cost argument: each recurring WA costs 10+ minutes in a contest (debugging + penalty time). If journaling eliminates 3 recurring mistakes per contest, that is 30 minutes recovered — often enough for an additional problem. Over 20 contests, that is the equivalent of 10+ additional hours of productive contest time.
Follow-up: What is the minimum viable mistake journal — what is the least effort that still provides benefit?After every WA or TLE, write one line: the date, the mistake category (overflow, off-by-one, edge case, logic, reset), and a 5-word description. That is it. Even this minimal log, reviewed weekly, reveals patterns within 2-3 weeks. You do not need elaborate templates or detailed code diffs to get 80% of the benefit. The detailed analysis is nice-to-have for specific difficult bugs, but the category tagging alone drives the core insight.