C++ is a common choice for competitive programming because it is fast, has a strong Standard Template Library (STL), and gives you low-level control when you need it. This guide covers setup, core techniques, and a few patterns used in contests like ICPC and Codeforces.
Why C++ for Competitive Programming?
Speed Comparison
| Language | Execution Time (relative) | Memory |
|---|---|---|
| C++ | 1.0x (baseline) | Low |
| C | 1.0x | Low |
| Java | 1.5-2x | High |
| Python | 10-50x | Medium |
When you have a 1-2 second time limit and 10^8 operations, every millisecond counts.
Other Advantages
- ✅ STL — Built-in data structures (vectors, sets, maps, priority queues)
- ✅ Control — Manual memory management when needed
- ✅ Predictability — Consistent performance without GC pauses
- ✅ Community — Most competitive programming resources use C++
Essential Setup
Competitive Programming Template
#include <bits/stdc++.h>
using namespace std;
// Type aliases for faster typing
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<ll> vll;
// Debug macro (disabled in submissions)
#ifdef LOCAL
#define debug(x) cerr << #x << " = " << (x) << endl
#else
#define debug(x)
#endif
// Fast I/O
#define fast_io ios_base::sync_with_stdio(false); cin.tie(NULL);
// Common constants
const int INF = 1e9;
const ll LINF = 1e18;
const int MOD = 1e9 + 7;
int main() {
fast_io;
int t;
cin >> t;
while (t--) {
// Your solution here
}
return 0;
}
Compile Command
# Standard compilation
g++ -std=c++17 -O2 -o solution solution.cpp
# With warnings and debug info
g++ -std=c++17 -O2 -Wall -Wextra -g -DLOCAL -o solution solution.cpp
STL Essentials
Vector (Dynamic Array)
vector<int> v;
v.push_back(10); // Add element
v.pop_back(); // Remove last
v.size(); // Current size
v.empty(); // Check if empty
v.clear(); // Remove all
v.front(); v.back(); // First/last element
v[i]; // Access by index (no bounds check)
v.at(i); // Access with bounds check
// Initialization
vector<int> v1(n); // n elements, default value (0)
vector<int> v2(n, -1); // n elements, all -1
vector<int> v3 = {1,2,3}; // Initializer list
vector<vector<int>> grid(n, vector<int>(m, 0)); // 2D grid
Set and Map (Balanced BST)
// Set - ordered unique elements
set<int> s;
s.insert(5); // Add element
s.erase(5); // Remove element
s.count(5); // Check existence (0 or 1)
s.find(5); // Iterator to element
*s.begin(); // Smallest element
*s.rbegin(); // Largest element
// Map - ordered key-value pairs
map<string, int> m;
m["hello"] = 5; // Insert/update
m.count("hello"); // Check key exists
for (auto& [key, value] : m) {
// Iterate
}
// Unordered versions (O(1) average, hash-based)
unordered_set<int> us;
unordered_map<string, int> um;
Priority Queue (Heap)
// Max heap (default)
priority_queue<int> maxHeap;
maxHeap.push(10);
maxHeap.top(); // Largest element
maxHeap.pop(); // Remove largest
// Min heap
priority_queue<int, vector<int>, greater<int>> minHeap;
minHeap.push(10);
minHeap.top(); // Smallest element
Algorithms
vector<int> v = {3, 1, 4, 1, 5, 9};
// Sorting
sort(v.begin(), v.end()); // Ascending
sort(v.begin(), v.end(), greater<int>()); // Descending
sort(v.begin(), v.end(), [](int a, int b) { // Custom
return a > b;
});
// Binary search (requires sorted array)
binary_search(v.begin(), v.end(), 4); // true/false
lower_bound(v.begin(), v.end(), 4); // Iterator to first >= 4
upper_bound(v.begin(), v.end(), 4); // Iterator to first > 4
// Min/max
*min_element(v.begin(), v.end());
*max_element(v.begin(), v.end());
// Sum
accumulate(v.begin(), v.end(), 0LL); // Use 0LL for long long
// Permutations
next_permutation(v.begin(), v.end()); // Lexicographically next
prev_permutation(v.begin(), v.end());
// Unique (remove consecutive duplicates)
v.erase(unique(v.begin(), v.end()), v.end());
Time Complexity Cheat Sheet
Know Your Limits
| Time Complexity | Max N (1 sec) | Example Operations |
|---|---|---|
| O(1) | Any | Array access, hash lookup |
| O(log N) | 10^18 | Binary search |
| O(√N) | 10^14 | Factorization |
| O(N) | 10^8 | Single loop |
| O(N log N) | 10^6 | Sorting, balanced BST |
| O(N²) | 10^4 | Nested loops |
| O(N³) | 500 | Triple nested loops |
| O(2^N) | 20-25 | Subsets, bitmask DP |
| O(N!) | 10-11 | Permutations |
Rule of Thumb
10^8 operations per second (rough estimate for online judges)
// If N = 10^5 and time limit = 1s:
// O(N²) = 10^10 operations → TLE!
// O(N log N) = ~1.7 × 10^6 operations → OK
Common Techniques
Prefix Sum
Precompute cumulative sums for O(1) range queries.
vector<int> arr = {1, 2, 3, 4, 5};
int n = arr.size();
// Build prefix sum
vector<ll> prefix(n + 1, 0);
for (int i = 0; i < n; i++) {
prefix[i + 1] = prefix[i] + arr[i];
}
// Query sum from index l to r (inclusive)
ll rangeSum = prefix[r + 1] - prefix[l];
Two Pointers
Efficiently process sorted arrays or find pairs.
// Find pair with target sum in sorted array
int left = 0, right = n - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) {
// Found!
break;
} else if (sum < target) {
left++;
} else {
right--;
}
}
Binary Search on Answer
When you can't directly compute the answer, but can check if a value is valid.
// Find minimum X such that condition is satisfied
ll lo = 0, hi = 1e18;
while (lo < hi) {
ll mid = lo + (hi - lo) / 2;
if (isValid(mid)) {
hi = mid; // mid might be answer, search lower
} else {
lo = mid + 1; // mid too small
}
}
// Answer is lo
Modular Arithmetic
For problems requiring answers modulo 10^9 + 7.
const int MOD = 1e9 + 7;
// Addition
ll add(ll a, ll b) {
return ((a % MOD) + (b % MOD)) % MOD;
}
// Multiplication
ll mul(ll a, ll b) {
return ((a % MOD) * (b % MOD)) % MOD;
}
// Power (fast exponentiation)
ll power(ll base, ll exp, ll mod = MOD) {
ll result = 1;
base %= mod;
while (exp > 0) {
if (exp & 1) result = result * base % mod;
base = base * base % mod;
exp >>= 1;
}
return result;
}
// Modular inverse (when MOD is prime)
ll modInverse(ll a) {
return power(a, MOD - 2);
}
Common Mistakes to Avoid
1. Integer Overflow
// ❌ Overflow with int
int a = 100000, b = 100000;
int product = a * b; // Overflow!
// ✅ Use long long
ll product = (ll)a * b; // Cast before multiplication
2. Array Index Out of Bounds
// ❌ Accessing beyond array
int arr[100];
arr[100] = 5; // Undefined behavior!
// ✅ Stay within bounds
arr[99] = 5;
3. Wrong Loop Variable
// ❌ Common bug in nested loops
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; i++) { // Bug: i++ instead of j++
...
}
}
4. Forgetting to Reset Globals
vector<int> adj[MAXN]; // Global adjacency list
void solve() {
// ❌ Forgetting to clear between test cases
// ✅ Clear at start of each test case
for (int i = 0; i < n; i++) adj[i].clear();
}
Practice Resources
Online Judges
| Platform | Focus | Difficulty |
|---|---|---|
| Codeforces | Contests, ratings | All levels |
| LeetCode | Interview prep | Medium-Hard |
| AtCoder | Clean problems | All levels |
| CSES | Fundamentals | Learning |
| HackerRank | Structured practice | Beginner |
Learning Path
- Week 1-2: STL basics, sorting, binary search
- Week 3-4: Two pointers, prefix sums, greedy
- Week 5-8: Dynamic programming basics
- Week 9-12: Graph algorithms (BFS, DFS, Dijkstra)
- Ongoing: Advanced topics (segment trees, DP optimization)
FAQ
Q: Should I use bits/stdc++.h in production code?
A: No! It's non-standard and slow to compile. Use it only in competitive programming for convenience.
Q: Why does my solution get TLE even with correct complexity?
A: Common causes: slow I/O (use fast_io), hidden constant factors, wrong complexity analysis, or edge cases causing worst-case behavior.
Q: Is it worth switching from Python to C++? A: For competitive programming, absolutely. For interviews, both work. Python is often too slow for time-constrained problems.
Q: How do I debug runtime errors on online judges? A: Test locally with various inputs, check array bounds, look for division by zero, and validate edge cases (n=0, n=1).
Practice C++ Online
No setup required — start coding immediately:
- AI C++ Compiler — Run C++ with AI-assisted debugging
- AI C Compiler — Compare with C performance
- AI Python Compiler — Prototype solutions quickly
Last updated: December 2025 | Written by Muhammed Ajmal U K