Skip to main content

CP Environment Setup

The Perfect CP Setup

A fast, efficient environment is crucial for competitive programming. Every second matters in contests. This guide covers everything from VS Code configuration to templates and workflow optimization.

VS Code Setup for CP

Essential Extensions

Install these extensions for the best CP experience:

VS Code Settings for CP

Add to your settings.json (Ctrl+Shift+P → “Open Settings JSON”):

Keyboard Shortcuts

Add to keybindings.json (Ctrl+Shift+P → “Open Keyboard Shortcuts JSON”):

Folder Structure

Organize your CP workspace:

The Ultimate CP Template

Standard Template


Specialized Templates

Interactive Problems Template

Interactive Problem Rules:
  1. Always flush after each output: cout.flush() or endl
  2. Don’t print extra output
  3. Read the response before the next query
  4. Some judges require \n instead of endl

Multi-Test with Global Reset


Input/Output Patterns

Reading Different Input Formats

Output Patterns


Stress Testing Script

stress.cpp

stress.bat (Windows)

stress.sh (Linux/Mac)


Compile Commands

Standard Compilation

tasks.json for VS Code

Create .vscode/tasks.json:

VS Code Snippets

Create .vscode/cpp.json or add to User Snippets:

Online Judge Tools

Competitive Companion (Browser Extension)

  1. Install Competitive Companion for Chrome/Firefox
  2. It automatically parses problem statements and test cases
  3. Works with Codeforces, AtCoder, CSES, and more

cp-tools for VS Code

Use with Competitive Programming Helper extension:
  1. Click on the problem in browser with Competitive Companion
  2. Test cases auto-download to your workspace
  3. Run all test cases with one click

Quick Reference Card

Complexity Limits

Common Mistakes Checklist

  • Integer overflow → Use long long
  • Array out of bounds → Check indices
  • Uninitialized variables → Initialize everything
  • Wrong loop bounds → Off-by-one errors
  • Forgot to reset globals → Clear between test cases
  • TLE → Check complexity, optimize I/O
  • WA on edge cases → Test n=0, n=1, negative numbers

Key Takeaways

Fast I/O

Always use ios::sync_with_stdio(false) and cin.tie(nullptr).

Templates Save Time

Have snippets ready for common patterns.

Stress Test

Generate random tests to find edge cases.

Debug Locally

Use -DLOCAL flag for debug output.

Next Up

Chapter 3: STL Mastery

Master the Standard Template Library for competitive programming.

Interview Deep-Dive

Strong Answer:
  • Templates eliminate repetitive boilerplate that wastes time and introduces bugs under contest pressure. Fast I/O setup, type aliases, common macros, and debug utilities are identical across problems — typing them from scratch each time is pure waste.
  • For solo contests, maximize personal convenience: heavy macro usage, short aliases, everything you personally know. For ICPC team contests, the template must be readable by all three team members. I would reduce macros to the universally understood ones (all, sz, pb), keep type aliases standard (ll, vi, pii), and ensure the debug system compiles out cleanly with the LOCAL flag.
  • The template should include: fast I/O, type aliases, a solve() function with test case loop, debug macros gated behind LOCAL, and direction arrays for grid problems. It should NOT include: algorithm implementations (segment tree, DSU) — those belong in a separate code library that you copy when needed.
  • A good template is under 40 lines. Longer templates slow down compilation, increase the chance of IDE errors, and make it harder to find your actual solution code during debugging.
Follow-up: What compiler flags should be in your default build configuration, and why?-std=c++17 for structured bindings and if-constexpr. -O2 for optimization (matches most online judges). -Wall -Wextra -Wshadow for catching bugs at compile time — shadowed variables are a common source of subtle bugs. -DLOCAL for enabling debug macros. For debugging sessions specifically: -fsanitize=address,undefined to catch memory errors and undefined behavior. For stress testing: -O2 without sanitizers for speed. I maintain two build tasks in VS Code: “Build (Debug)” with sanitizers and “Build (Submit)” with just O2.
Strong Answer:
  • AddressSanitizer (ASan) is a runtime tool that detects memory errors: out-of-bounds array access, use-after-free, stack buffer overflow, heap buffer overflow, and memory leaks. It instruments every memory access with bounds checks and maintains a shadow memory map to track which bytes are valid.
  • Concrete example: you declare int arr[100] and somewhere in a loop you write to arr[100] (one past the end). Without ASan, this silently overwrites whatever is next in memory — maybe another variable, maybe the return address. Your program might produce a wrong answer, crash randomly, or appear to work correctly (the most dangerous outcome because you submit a buggy solution).
  • With ASan, the program immediately crashes with a detailed error message showing the exact line number, the invalid address, and the allocated buffer it tried to access past. Instead of spending 30 minutes tracking down a mysterious WA, you fix it in 30 seconds.
  • Runtime overhead: ASan slows execution by about 2x and increases memory usage by 2-3x. This means you should NOT use it on the actual submission (the online judge does not have it enabled and the overhead might cause TLE). Use it for local testing only, then compile without it for submission.
Follow-up: What about UndefinedBehaviorSanitizer — what does it catch that ASan does not?UBSan catches undefined behavior that does not involve memory access: signed integer overflow (the number one CP bug), division by zero, null pointer dereference, shift operations by negative or too-large amounts, and misaligned pointer access. The key one for CP is signed overflow: int a = 1e9; int b = a * 2; is undefined behavior in C++ (the result exceeds INT_MAX). Without UBSan, this silently wraps around to a garbage value. With UBSan, you get an immediate error message pinpointing the line. Use both together: -fsanitize=address,undefined.
Strong Answer:
  • Minute 1-3: Install g++ (via MinGW on Windows or build-essential on Linux). Verify with g++ --version. This is the non-negotiable prerequisite.
  • Minute 4-7: Create a single template file with fast I/O, the solve() function with test case loop, using ll = long long, and basic macros. Save it to a known location. Show them how to copy it to start a new problem.
  • Minute 8-10: Create an input.txt file in the same directory. Show them the workflow: paste sample input into input.txt, compile with g++ -O2 -o sol sol.cpp, run with ./sol < input.txt. This is the fastest possible feedback loop.
  • Minute 11-13: Set up VS Code with the Code Runner extension configured to compile and run against input.txt with a single keyboard shortcut (Ctrl+Alt+N). Show them how to switch between problems by editing input.txt.
  • Minute 14-15: Walk through one complete cycle: open template, read a problem, edit solve(), paste sample into input.txt, press the run shortcut, verify output matches expected. Confirm they can do this independently.
  • What I explicitly skip: debug macros (too confusing for beginners), stress testing setup (premature), VS Code snippets (add later), and Competitive Companion (add after they are comfortable with manual input). Keep the initial setup minimal so they are not overwhelmed.
Follow-up: What do you add in the second session, after they have done their first contest?Debug macros with the LOCAL flag, a pre-submit checklist (overflow, bounds, reset, format), and the Competitive Companion browser extension for automatic test case parsing. After their first contest, they will have experienced specific pain points (slow input parsing, difficulty comparing output, forgetting edge cases) and the additions will feel motivated rather than arbitrary.