Fast I - O in Java in Competitive Programming - GeeksforGeeks
Fast I - O in Java in Competitive Programming - GeeksforGeeks
DSA for Beginners DSA Tutorial Data Structures Algorithms Array Strings Linked List Stack Queue Tree Graph Searching Sorting Recursion Dynamic Programming Binar
Competitive Programming (CP) Using Java in competitive programming is not something many people would
Handbook with Complete Roadmap suggest just because of its slow input and output, and well indeed it is slow.
Mathematics for Competitive In this article, we have discussed some ways to get around the difficulty and
Top Technology Intervene For 10 Best O
Programming
change the verdict from TLE to (in most cases) AC. Accessibility Courses
1. 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 the input stream(e.g. System.in). The following
program many times gets time limit exceeded verdict and therefore not of much
use.
Java
Java
StringTokenizer st
= new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int count = 0;
while (n-- > 0) {
int x = Integer.parseInt(br.readLine());
if (x % k == 0)
count++;
}
System.out.println(count);
}
}
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. These get 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.
Java
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
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. These get accepted
with a surprising time of just 0.28 s. Although this is ultra-fast, it is clearly not an
easy method to remember.
Java
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
if (neg)
return -ret;
return ret;
}
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;
return ret;
}
Suggested Read:
Enormous Input Test designed to check the fast input handling of your language.
Timings of all programs are noted from SPOJ.
If you like GeeksforGeeks and would like to contribute, you can also write an
article and mail your article to review-team@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
Related Courses
Build your Java Foundation strong with our Java Programming Foundation –
Self Paced Course. This self-paced course gives you the right start with
JAVA basics, variables and data types, operators, strings & much more.
This course is designed for absolute beginners looking to sharpen their
skills to the next level. Start Learning Now!
Feeling lost in the world of random DSA topics, wasting time without progress?
It's time for a change! Join our DSA course, where we'll guide you on an exciting
journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course,
trusted by over 100,000 geeks!
DSA in C++
DSA in Java
DSA in Python
DSA in JavaScript
Recommended Problems
Solve Problems
Frequently asked DSA Problems
Previous Next
Similar Reads
How to Print Fast Output in Competitive Java Competitive Programming Setup in
Programming using Java? VS Code with Fast I/O and Snippets
Complete Tutorials
Learn Algorithms with Javascript | DSA DSA Crash Course | Revision Checklist
using JavaScript Tutorial with Interview Guide
R Rishabh Mahrsee
Additional Information
Company Explore Languages DSA Data Science & HTML & CSS
About Us Job-A-Thon Hiring Python Data Structures ML HTML
A-143, 9th Floor, Sovereign Corporate
Tower, Sector-136, Noida, Uttar Pradesh - Challenge
Legal Java Algorithms Data Science With CSS
201305
Careers Hack-A-Thon C++ DSA for Beginners Python Bootstrap
In Media GfG Weekly Contest PHP Basic DSA Problems Data Science For Tailwind CSS
O line Classes Beginner
Contact Us GoLang DSA Roadmap SASS
(Delhi/NCR) Machine Learning
Advertise with us SQL Top 100 DSA LESS
DSA in JAVA/C++ Tutorial
GFG Corporate R Language Interview Problems Web Design
Master System ML Maths
Solution Android Tutorial DSA Roadmap by
Design Sandeep Jain Data Visualisation
Placement Training
Master CP Tutorial
Program All Cheat Sheets
GeeksforGeeks Pandas Tutorial
Apply for Mentor
Videos NumPy Tutorial
NLP Tutorial
Deep Learning
Tutorial
Grokking Modern
System Design
NCERT School Subjects Commerce Management & UPSC Study SSC/ BANKING
Solutions Mathematics Accountancy Finance Material SSC CGL Syllabus
Class 11 Chemistry Indian Economics HR Managament Geography Notes SBI Clerk Syllabus
Class 9 Social Science Microeconimics Finance Science and IBPS Clerk Syllabus
Class 8 English Grammar Statistics for Economics Technology Notes SSC CGL Practice