Fast Input/Output
Fast Input/Output
Fast Input/Output
In competitive programming, some problems have very large inputs — hundreds of thousands or even millions of lines. Python's default input() function has noticeable overhead, and slow I/O alone can cause a correct solution to exceed the time limit. This lesson covers how to read and write data as fast as possible in Python.
Why input() Is Slow
Python's built-in input() does several things behind the scenes on every call: it flushes buffers, handles encoding, and processes the string. For a few hundred lines this is invisible. For 10^6 lines it adds up to seconds.
sys.stdin bypasses most of that overhead and reads raw bytes directly from the input stream.
sys.stdin.readline
The simplest upgrade — drop-in replacement for input():
Put this line at the top of your solution. Now every call to input() uses the faster version transparently. One important difference: sys.stdin.readline keeps the trailing newline \n, so use .strip() when reading strings:
.split() without arguments strips all whitespace including \n, so for integer arrays you don't need .strip() at all.
Reading All Input at Once
Even faster: read the entire input in one system call, then process it:
This gives you a flat list of all whitespace-separated tokens. Access them with an index:
For very large inputs this is the fastest reading method in Python. The entire file is loaded in one I/O operation.
A cleaner pattern using an iterator:
sys.stdout.write
print() also has overhead — it converts arguments, handles separators and endings, and flushes. For large output, use sys.stdout.write instead:
If you have many lines to output, collect them all first and write once:
One write call for the entire output is significantly faster than thousands of print() calls.
sys.setrecursionlimit
Python's default recursion limit is 1000. Any recursive solution — DFS, recursive DP, divide and conquer — will hit RecursionError on large inputs without raising this limit. Always set it at the very top of your solution:
This does not affect speed directly, but it prevents crashes that waste submission attempts.
PyPy vs CPython
Many online judges offer PyPy as an alternative to CPython. PyPy is a JIT-compiled Python interpreter that runs 5–10× faster than CPython on typical CP code — often making a slow Python solution fast enough to pass.