Fast I/O in Java in Competitive Programming
Using Java in competitive programming is not something many people would suggest just because of its slow input and output, and well indeed it is slow.
In this article, we have discussed some ways to get around the difficulty and change the verdict from TLE to (in most cases) AC.
For all the Programs below
Input:
7 3 1 51 966369 7 9 999996 11
Output:
4
-
Scanner Class – (easy, less typing, but not recommended very slow, refer this for reasons of slowness): In most of the cases we get TLE while using scanner class. It uses built-in nextInt(), nextLong(), nextDouble methods to read the desired object after initiating scanner object with input stream.(eg System.in). The following program many a times gets time limit exceeded verdict and therefore not of much use.
// Working program using Scannerimportjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.util.Scanner;publicclassMain{publicstaticvoidmain(String[] args){Scanner s =newScanner(System.in);intn = s.nextInt();intk = s.nextInt();intcount =0;while(n-- >0){intx = s.nextInt();if(x%k ==0)count++;}System.out.println(count);}}chevron_rightfilter_none - BufferedReader – (fast, but not recommended as it requires lot of typing): The Java.io.BufferedReader class reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. With this method we will have to parse the value every time for desired type. Reading multiple words from single line adds to its complexity because of the use of Stringtokenizer and hence this is not recommended. This gets accepted with a running time of approx 0.89 s.but still as you can see it requires a lot of typing all together and therefore method 3 is recommended.
// Working program using BufferedReaderimportjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.util.StringTokenizer;publicclassMain{publicstaticvoidmain(String[] args)throwsIOException{BufferedReader br =newBufferedReader(newInputStreamReader(System.in));StringTokenizer st =newStringTokenizer(br.readLine());intn = Integer.parseInt(st.nextToken());intk = Integer.parseInt(st.nextToken());intcount =0;while(n-- >0){intx = Integer.parseInt(br.readLine());if(x%k ==0)count++;}System.out.println(count);}}chevron_rightfilter_none - Userdefined FastReader Class- (which uses bufferedReader and StringTokenizer): This method uses the time advantage of BufferedReader and StringTokenizer and the advantage of user defined methods for less typing and therefore a faster input altogether. This gets accepted with a time of 1.23 s and this method is very much recommended as it is easy to remember and is fast enough to meet the needs of most of the question in competitive coding.
// Working program with FastReaderimportjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.util.Scanner;importjava.util.StringTokenizer;publicclassMain{staticclassFastReader{BufferedReader br;StringTokenizer st;publicFastReader(){br =newBufferedReader(newInputStreamReader(System.in));}String next(){while(st ==null|| !st.hasMoreElements()){try{st =newStringTokenizer(br.readLine());}catch(IOException e){e.printStackTrace();}}returnst.nextToken();}intnextInt(){returnInteger.parseInt(next());}longnextLong(){returnLong.parseLong(next());}doublenextDouble(){returnDouble.parseDouble(next());}String nextLine(){String str ="";try{str = br.readLine();}catch(IOException e){e.printStackTrace();}returnstr;}}publicstaticvoidmain(String[] args){FastReader s=newFastReader();intn = s.nextInt();intk = s.nextInt();intcount =0;while(n-- >0){intx = s.nextInt();if(x%k ==0)count++;}System.out.println(count);}}chevron_rightfilter_none - Using Reader Class: There is yet another fast way through the problem, I would say the fastest way but is not recommended since it requires very cumbersome methods in its implementation. It uses inputDataStream to read through the stream of data and uses read() method and nextInt() methods for taking inputs. This is by far the fastest ways of taking input but is difficult to remember and is cumbersome in its approach. Below is the sample program using this method.
This gets accepted with a surprising time of just 0.28 s. Although this is ultra fast, it is clearly not an easy method to remember.
// Working program using Reader Classimportjava.io.DataInputStream;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStreamReader;importjava.util.Scanner;importjava.util.StringTokenizer;publicclassMain{staticclassReader{finalprivateintBUFFER_SIZE =1<<16;privateDataInputStream din;privatebyte[] buffer;privateintbufferPointer, bytesRead;publicReader(){din =newDataInputStream(System.in);buffer =newbyte[BUFFER_SIZE];bufferPointer = bytesRead =0;}publicReader(String file_name)throwsIOException{din =newDataInputStream(newFileInputStream(file_name));buffer =newbyte[BUFFER_SIZE];bufferPointer = bytesRead =0;}publicString readLine()throwsIOException{byte[] buf =newbyte[64];// line lengthintcnt =0, c;while((c = read()) != -1){if(c =='\n')break;buf[cnt++] = (byte) c;}returnnewString(buf,0, cnt);}publicintnextInt()throwsIOException{intret =0;bytec = read();while(c <=' ')c = read();booleanneg = (c =='-');if(neg)c = read();do{ret = ret *10+ c -'0';}while((c = read()) >='0'&& c <='9');if(neg)return-ret;returnret;}publiclongnextLong()throwsIOException{longret =0;bytec = read();while(c <=' ')c = read();booleanneg = (c =='-');if(neg)c = read();do{ret = ret *10+ c -'0';}while((c = read()) >='0'&& c <='9');if(neg)return-ret;returnret;}publicdoublenextDouble()throwsIOException{doubleret =0, div =1;bytec = read();while(c <=' ')c = read();booleanneg = (c =='-');if(neg)c = read();do{ret = ret *10+ c -'0';}while((c = read()) >='0'&& c <='9');if(c =='.'){while((c = read()) >='0'&& c <='9'){ret += (c -'0') / (div *=10);}}if(neg)return-ret;returnret;}privatevoidfillBuffer()throwsIOException{bytesRead = din.read(buffer, bufferPointer =0, BUFFER_SIZE);if(bytesRead == -1)buffer[0] = -1;}privatebyteread()throwsIOException{if(bufferPointer == bytesRead)fillBuffer();returnbuffer[bufferPointer++];}publicvoidclose()throwsIOException{if(din ==null)return;din.close();}}publicstaticvoidmain(String[] args)throwsIOException{Reader s=newReader();intn = s.nextInt();intk = s.nextInt();intcount=0;while(n-- >0){intx = s.nextInt();if(x%k ==0)count++;}System.out.println(count);}}chevron_rightfilter_none
Suggested Read: Enormous Input Test designed to check the fast input handling of your language.Timings of all programs are noted from SPOJ.
This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Recommended Posts:
- Fast I/O for Competitive Programming
- Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
- Input/Output from external file in C/C++, Java and Python for Competitive Programming
- Input/Output from external file in C/C++, Java and Python for Competitive Programming | Set 2
- Java tricks for competitive programming (for Java 8)
- How can competitive programming help you get a job?
- Python in Competitive Programming
- How to become a master in competitive programming?
- C++ tricks for competitive programming (for C++ 11)
- A Better Way To Approach Competitive Programming
- Bit Tricks for Competitive Programming
- How to begin with Competitive Programming?
- Competitive Programming: Conquering a given problem
- How to read Competitive Programming Questions?
- Bitwise Hacks for Competitive Programming



