Master fast I/O in competitive programming — why cin/cout is slow, how sync_with_stdio and tie affect speed, custom fast readers in C++, Python stdin tricks, complete templates for C++ and Python with all optimizations, and when I/O speed is the difference between AC and TLE.
Why I/O Speed Matters
In competitive programming, your solution must complete within a strict time limit — usually 1-3 seconds. For problems with large inputs (n = 10^5 to 10^6), the time spent just reading input can consume a significant portion of your time budget.
Concrete example:
| Slow C++ cin | ~2.0 seconds |
| Fast C++ (sync off) | ~0.2 seconds |
| Custom fast reader | ~0.1 seconds |
| Python built-in input() | ~3.0 seconds for 10^6 integers |
| Python sys.stdin | ~0.5 seconds |
If your algorithm is O(n log n) in 0.5 seconds but I/O takes 2 seconds — you TLE. This is why fast I/O is a fundamental skill.
Complete C++ Template
#include <bits/stdc++.h>
using namespace std;
// Typedefs
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<pii> vpii;
// Macros
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define sz(x) (int)(x).size()
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define REP(i,n) for(int i=0;i<(n);i++)
// Constants
const int INF = 1e9 + 5;
const ll LLINF = 2e18;
const int MOD = 1e9 + 7;
const double PI = acos(-1.0);
void solve() {
// Your solution here
int n;
cin >> n;
vector<int> arr(n);
for (int& x : arr) cin >> x;
// Process...
cout << 42 << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t = 1;
cin >> t; // Comment this line if no multiple test cases
while (t--) {
solve();
}
return 0;
}
Custom Fast Reader (Fastest Possible C++)
For extreme cases (n = 10^7 or more) where even optimized cin is too slow:
#include <bits/stdc++.h>
using namespace std;
// Custom fast reader using raw system calls
namespace fastio {
const int BUFSIZE = 1 << 22; // 4 MB buffer
char buf[BUFSIZE];
int bufpos = 0, buflen = 0;
inline char gc() {
if (bufpos == buflen) {
buflen = fread(buf, 1, BUFSIZE, stdin);
bufpos = 0;
if (!buflen) return EOF;
}
return buf[bufpos++];
}
inline int read_int() {
int x = 0;
char c = gc();
bool neg = false;
while (c != '-' && (c < '0' || c > '9')) c = gc();
if (c == '-') { neg = true; c = gc(); }
while (c >= '0' && c <= '9') { x = x*10 + (c-'0'); c = gc(); }
return neg ? -x : x;
}
inline long long read_ll() {
long long x = 0;
char c = gc();
bool neg = false;
while (c != '-' && (c < '0' || c > '9')) c = gc();
if (c == '-') { neg = true; c = gc(); }
while (c >= '0' && c <= '9') { x = x*10 + (c-'0'); c = gc(); }
return neg ? -x : x;
}
}
int main() {
int n = fastio::read_int();
vector<int> arr(n);
for (int& x : arr) x = fastio::read_int();
// ...
}
This is typically 2-3x faster than optimized cin for very large inputs.
Python Fast I/O
# SLOW: input() is the standard function
n = int(input())
arr = list(map(int, input().split()))
For n = 10^5, this might be fine. For n = 10^6, it's often too slow.
Solution: Use sys.stdin
import sys
input = sys.stdin.readline # Override input() globally
n = int(input())
arr = list(map(int, input().split()))
This is 3-5x faster than the default input().
Even Faster: Read All at Once
import sys
# Method 1: Read all input at once
data = sys.stdin.read().split()
idx = 0
n = int(data[idx]); idx += 1
arr = [int(data[idx+i]) for i in range(n)]; idx += n
Fastest: sys.stdin.buffer (Binary Mode)
import sys
input = sys.stdin.buffer.readline
n = int(input())
arr = list(map(int, input().split()))
Binary mode avoids string decoding overhead — fastest pure Python I/O.
Complete Python Template
import sys
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify, nlargest, nsmallest
from functools import lru_cache
from itertools import combinations, permutations, product
from math import gcd, lcm, log2, sqrt, inf, ceil, floor
from bisect import bisect_left, bisect_right, insort
# Fast I/O
input = sys.stdin.readline
print = sys.stdout.write # Optional: for very fast output
# Or even simpler for most problems:
# input = lambda: sys.stdin.readline().rstrip()
def solve():
n = int(input())
arr = list(map(int, input().split()))
# Your solution
ans = max(arr)
sys.stdout.write(str(ans) + '\n')
t = int(input())
for _ in range(t):
solve()
Output Optimization
C++ Output
// SLOW: Multiple small writes
for (int x : arr) cout << x << ' ';
// FAST: Build string first, write once
string out;
out.reserve(arr.size() * 12);
for (int x : arr) {
out += to_string(x);
out += ' ';
}
cout << out;
// Or use printf for formatted output (still fast without sync)
// But don't mix with cin after sync_with_stdio(false)!
Python Output
# SLOW: print() inside a loop with large output
for x in arr:
print(x)
# FAST: Join and print once
sys.stdout.write('\n'.join(map(str, arr)) + '\n')
# Or:
print(*arr, sep='\n') # Still better than printing individually
Common I/O Patterns in Competitive Programming
# Read a single integer
n = int(input())
# Read a line of space-separated integers
arr = list(map(int, input().split()))
# Read n lines, each with k integers
grid = [list(map(int, input().split())) for _ in range(n)]
# Read a string
s = input().strip()
# Read t test cases
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
# solve(n, m)
# Read edges of a graph
n, m = map(int, input().split())
adj = [[] for _ in range(n)]
for _ in range(m):
u, v = map(int, input().split())
u -= 1; v -= 1 # 0-indexed
adj[u].append(v)
adj[v].append(u)
When I/O Optimization Is Critical
| n ≤ 10^4 | Any I/O method works fine |
| n ≤ 10^5 | Standard cin/input() with basic optimization |
| n ≤ 10^6 | MUST use fast I/O (sync_with_stdio, sys.stdin) |
| n ≤ 10^7 | Custom fast reader in C++; Python may TLE regardless |
| n ≤ 10^8 | C++ custom reader; Python is unlikely to pass |
Summary
Fast I/O is a low-effort, high-reward optimization that every competitive programmer must implement automatically:
C++:
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// Use '\n' not endl
Python:
import sys
input = sys.stdin.readline
These two changes take 5 seconds to type and can prevent TLE on large-input problems. Add them to every solution as a reflex.
*Next Lesson: Contest Strategies*