Speed Input Reading
JAVA
If you find that you are timing out using Java's native java.util.Scanner
class consider using faster input reading.
A modified and much more performant version of the Scanner class can be copied from here.
Sample usage:
public class Main {
// Paste Scanner class here.
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
System.out.println(sc.nextInt());
}
}
The java.io.BufferedReader
is also much more performant than the native Scanner.
Sample usage of BufferedReader:
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println(Integer.parseInt(reader.readLine()));
}
}
Similarly, java.io.BufferedWriter
can be used for faster output.
Sample usage of BufferedWriter:
public class Main {
public static void main(String[] args) throws IOException {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512);
out.write(String.valueOf(100));
out.write('\n');
out.write("Hello, World!");
out.flush();
}
}
PYTHON
Python is also really slow. You can use the language pypy3 optimised for speed, but might memory overflow.
Try putting this at the top of your Python 3 code for a speed boost.
from sys import stdin
input = stdin.readline
Sample usage:
from sys import stdin
input = stdin.readline
x = input()