[Algorithm] Fast I/O Methods in Python

Faster Ways to Handle Input

In competitive programming or algorithm challenges, using the standard input() can sometimes lead to a TLE (Time Limit Exceeded). Here is how to read data more efficiently using sys.stdin.readline.

Reading Strings

Reading a Single Line

Python
import sys
s = sys.stdin.readline().rstrip()
  • Note
    • sys.stdin.readline() includes a newline character (\n) at the end of the string.
    • So strip it with .rstrip() or .strip(). .rstrip() removes trailing whitespace and newlines on the right, and .strip() removes them on both ends. To remove only the newline, use .rstrip('\n').

Reading into a List

1. Creating a list of characters

Python
import sys
char_list = list(sys.stdin.readline().rstrip())
  • This approach stores each individual character of the input into a list.

2. Creating a list of words

Python
import sys
word_list = sys.stdin.readline().rstrip().split()
  • Assuming the input is space-separated, this stores each word as an element in the list.

Reading Numbers

Multiple Integers in One Line

Python
import sys
a, b = map(int, sys.stdin.readline().split())
  • Good to Know
    • The split() function divides a string based on a delimiter.
    • If you leave the arguments empty, it splits the string on whitespace (spaces, tabs, newlines) and treats consecutive whitespace as one separator.