DSA Notes
Master fast I/O techniques in C++, Java, and Python to avoid TLE in competitive programming contests.
Why I/O Speed Matters
In competitive programming, time limits are tight — typically 1-2 seconds for C++ and 3-5 seconds for Python. When your problem involves reading 10^6 integers, slow I/O can be the difference between Accepted and Time Limit Exceeded (TLE). I have seen students lose contests not because their algorithm was wrong, but because cin was too slow without proper configuration.
C++: The Critical Optimization
The Problem with cin/cout
By default, C++ synchronizes cin/cout with C's scanf/printf to allow mixing both in the same program. This synchronization adds significant overhead. Additionally, cin is tied to cout, meaning cout flushes before every cin read.
The Fix: Two Magic Lines
ios_base::sync_with_stdio(false);
cin.tie(NULL);The first line disables synchronization with C I/O. The second unties cin from cout. Together, they make cin/cout roughly as fast as scanf/printf.
Important: After sync_with_stdio(false), do NOT mix cin/cout with scanf/printf in the same program. Pick one style.
Benchmark Comparison
Reading 10^7 integers:
| Method | Time |
|---|---|
scanf | ~0.9s |
cin (default) | ~2.5s |
cin (with sync disabled) | ~0.8s |
Custom getchar reader | ~0.4s |
scanf/printf: The C Way
Still widely used by competitive programmers who want guaranteed speed:
Format specifiers: %d (int), %lld (long long), %f (float), %lf (double), %s (string/char array), %c (char).
Ultra-Fast: Custom getchar Reader
For problems with extremely large input (10^7+ numbers), some contestants use a custom reader that processes input character by character:
This avoids all formatting overhead. Use it only when I/O is the proven bottleneck.
Avoid endl, Use "\n"
endl flushes the buffer every time it is called. With 10^5 output lines, this creates 10^5 flush operations. Use "\n" instead:
Java: BufferedReader and PrintWriter
Java's Scanner class is notoriously slow due to regex-based parsing. Use BufferedReader and StreamTokenizer instead:
Slow (Scanner)
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();Fast (BufferedReader + StringTokenizer)
Even Faster (StreamTokenizer)
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken(); int n = (int) in.nval;Benchmark (Reading 10^6 integers in Java)
| Method | Time |
|---|---|
| Scanner | ~3.5s |
| BufferedReader + split | ~1.2s |
| BufferedReader + StringTokenizer | ~0.8s |
| StreamTokenizer | ~0.6s |
Python: The Slowest but Improvable
Python is inherently slow for I/O, but there are tricks to minimize the damage.
Use sys.stdin Instead of input()
sys.stdin.readline is roughly 3x faster than the built-in input() because it skips the prompt handling.
Read All Input at Once
For very large inputs, read everything in one system call:
Output: Join and Print Once
# SLOW: print in a loop
for x in result:
print(x)
# FAST: single print with join
print("\n".join(map(str, result)))
# FASTEST: write to stdout directly
sys.stdout.write("\n".join(map(str, result)) + "\n")Use PyPy When Available
PyPy is typically 5-10x faster than CPython for algorithmic code. Most platforms (Codeforces, AtCoder) offer PyPy as a submission option. If your Python solution gets TLE, try PyPy before rewriting in C++.
When Does I/O Actually Matter?
I/O optimization matters when:
- Input size exceeds 10^5 elements
- You have many test cases (T ≤ 10^5) each with input
- The algorithm itself is O(n) or O(n log n) — I/O becomes a significant fraction of total time
I/O optimization does NOT matter when:
- Input is small (N ≤ 1000)
- Your algorithm is O(n²) or worse — the algorithm dominates
- You are using Python (algorithm speed is usually the bottleneck, not I/O)
Complete C++ Template with Fast I/O
This template covers 95% of competitive programming problems. Memorize it.
Language-Specific Gotchas
C++: Mixing cin and getline
A common bug: after reading an integer with cin >> n, calling getline() reads the leftover newline character. Fix:
int n;
cin >> n;
cin.ignore(); // Consume the leftover newline
string line;
getline(cin, line); // Now works correctlyPython: The map(int, input().split()) Pattern
This is the standard way to read multiple integers on one line in Python:
n, m = map(int, input().split()) # Two integers
arr = list(map(int, input().split())) # Array of integersJava: The System.out.println Trap
Each System.out.println() call can be slow due to auto-flushing. Buffer your output:
Real Contest Scenarios
Scenario 1: "My solution is O(n) but I still get TLE"
This almost always means I/O is the bottleneck. Check:
- Are you using
cinwithoutsync_with_stdio(false)? - Are you using
endlinstead of"\n"? - For Python: are you using
input()instead ofsys.stdin.readline?
Scenario 2: "It works locally but TLE on judge"
Online judges have slower I/O than your machine. The judge reads from stdin pipe, which behaves differently from terminal input. Always use fast I/O even if your local tests pass without it.
Scenario 3: "My Python solution is 3x the time limit"
Options in order of effort:
- Switch to PyPy (often 5-10x speedup, zero code changes)
- Use
sys.stdin.buffer.read()and pre-parse all input - Avoid creating unnecessary objects (list comprehensions over loops)
- If nothing works, rewrite in C++ (last resort)
Summary of Best Practices
| Language | Input | Output | Extra |
|---|---|---|---|
| C++ | ios_base::sync_with_stdio(false); cin.tie(NULL); | Use "\n" not endl | Consider scanf for huge input |
| Java | BufferedReader + StringTokenizer | PrintWriter with flush() at end | Avoid Scanner completely |
| Python | sys.stdin.readline or sys.stdin.buffer.read() | "\n".join() + single print | Use PyPy when available |
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Fast Input/Output for Competitive Programming.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, competitive, programming, fast
Related Data Structures & Algorithms Topics