Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Fast I - O in Java in Competitive Programming - GeeksforGeeks

The document discusses fast input/output methods in Java for competitive programming problems to avoid Time Limit Exceeded (TLE) errors. It compares the Scanner class, BufferedReader, and a custom FastReader class. The Scanner class is slow and often causes TLE. BufferedReader is faster but requires parsing input and is verbose. The custom FastReader class leverages BufferedReader and StringTokenizer for fast input with less code. It is recommended for competitive programming problems requiring efficient I/O.

Uploaded by

surafelhns
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Fast I - O in Java in Competitive Programming - GeeksforGeeks

The document discusses fast input/output methods in Java for competitive programming problems to avoid Time Limit Exceeded (TLE) errors. It compares the Scanner class, BufferedReader, and a custom FastReader class. The Scanner class is slow and often causes TLE. BufferedReader is faster but requires parsing input and is verbose. The custom FastReader class leverages BufferedReader and StringTokenizer for fast input with less code. It is recommended for competitive programming problems requiring efficient I/O.

Uploaded by

surafelhns
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

DSA Tutorials ML & Data Science Web Development Practice Sign In

DSA for Beginners DSA Tutorial Data Structures Algorithms Array Strings Linked List Stack Queue Tree Graph Searching Sorting Recursion Dynamic Programming Binar

Explore Our Geeks Community


Fast I/O in Java in Competitive Programming
Recently Published
Competitive Programming - A
Complete Guide Read Discuss(20+) Courses Practice

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

Number Theory for CP Example:


Read

Bit Manipulation for CP Input:


7 3
Combinatorics for CP 1
51
Greedy for CP
966369
7
Array based concepts for CP
9 experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
We use cookies to ensure you have the best browsing Got It !

999996
Dynamic Programming (DP) for
CP 11
Output:
4

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

// Working program using Scanner


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int k = s.nextInt();
int count = 0;
while (n-- > 0) {
int x = s.nextInt();
if (x % k == 0)
count++;
}
System.out.println(count);
}
}

2. BufferedReader (fast, but not recommended as it requires a lot of typing):

The Java.io.BufferedReader class reads text from a character-input stream,


buffering characters to provide for the efficient reading of characters, arrays, and
lines. With this method, we will have to parse the value every time for the
desired type. Reading multiple words from a single line adds to its complexity
because of the use of Stringtokenizer and hence this is not recommended. These
get accepted with a running time of approx 0.89 s.but still as you can see it
requires a lot of typing altogether and therefore method 3 is recommended.

Java

// Working program using BufferedReader


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {


public static void main(String[] args)
throws IOException
{

BufferedReader br = new BufferedReader(


new InputStreamReader(System.in));

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);
}
}

3.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. 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

// Working program with FastReader


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Main {


static class FastReader {
BufferedReader br;
StringTokenizer st;

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();
}

int nextInt() { return Integer.parseInt(next()); }

long nextLong() { return Long.parseLong(next()); }

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;
}
}

public static void main(String[] args)


{
FastReader s = new FastReader();
int n = s.nextInt();
int k = s.nextInt();
int count = 0;
while (n-- > 0) {
int x = s.nextInt();
if (x % k == 0)
count++;
}
System.out.println(count);
}
}

4.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. 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

// Working program using Reader Class


import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Main {


static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;

public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}

public Reader(String file_name) throws IOException


{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}

public String readLine() throws IOException


{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}

public int nextInt() throws IOException


{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');

if (neg)
return -ret;
return ret;
}

public long nextLong() throws IOException


{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}

public double nextDouble() throws IOException


{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (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;
return ret;
}

private void fillBuffer() throws IOException


{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}

private byte read() throws IOException


{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}

public void close() throws IOException


{
if (din == null)
return;
din.close();
}
}

public static void main(String[] args)


throws IOException
{
Reader s = new Reader();
int n = s.nextInt();
int k = s.nextInt();
int count = 0;
while (n-- > 0) {
int x = s.nextInt();
if (x % k == 0)
count++;
}
System.out.println(count);
}
}

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

Java Programming Foundation – Self Paced Course

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

Last Updated : 31 May, 2022 147

Previous Next

How to Setup IntelliJ IDEA For Efficiently Reading Input For


Java Competitive Programming Competitive Programming using
Environment? Java 8

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

Setting up Sublime Text For Competitive


Fast I/O for Competitive Programming in
Programming (C++) Using Fast Olympic
Python
Coding Plugin

How to Add Fast Scroller in RecyclerView


Fast I/O for Competitive Programming
using Recycle-Fast-Scroll?

Tips and Tricks for Competitive


Top Programming Languages For
Programmers | Set 2 (Language to be
Competitive Programming
used for Competitive Programming)

Dynamic Programming in Game Theory Java tricks for competitive programming


for Competitive Programming (for Java 8)

Complete Tutorials
Learn Algorithms with Javascript | DSA DSA Crash Course | Revision Checklist
using JavaScript Tutorial with Interview Guide

Learn Data Structures and Algorithms |


Java AWT Tutorial
DSA Tutorial

Mathematical and Geometric Algorithms


- Data Structure and Algorithm Tutorials

R Rishabh Mahrsee

Article Tags : Java-Competitive-Programming , Competitive Programming , DSA ,


Java

Practice Tags : Java

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

Python Computer DevOps Competitive System Design JavaScript


Python Science Git Programming What is System TypeScript
Programming GATE CS Notes AWS Top DS or Algo for Design ReactJS
Examples CP Monolithic and
Operating Systems Docker NextJS
Django Tutorial Top 50 Tree Distributed SD
Computer Network Kubernetes AngularJS
Python Projects Top 50 Graph High Level Design or
Database Azure NodeJS
Python Tkinter HLD
Management GCP Top 50 Array Express.js
Web Scraping System Low Level Design or
DevOps Roadmap Top 50 String Lodash
LLD
OpenCV Python So ware Top 50 DP
Crack System Design Web Browser
Tutorial Engineering
Top 15 Websites for Round
Python Interview Digital Logic Design CP
Question System Design
Engineering Maths
Interview Questions

Grokking Modern
System Design

NCERT School Subjects Commerce Management & UPSC Study SSC/ BANKING
Solutions Mathematics Accountancy Finance Material SSC CGL Syllabus

Class 12 Physics Business Studies Management Polity Notes SBI PO Syllabus

Class 11 Chemistry Indian Economics HR Managament Geography Notes SBI Clerk Syllabus

Class 10 Biology Macroeconomics Income Tax History Notes IBPS PO Syllabus

Class 9 Social Science Microeconimics Finance Science and IBPS Clerk Syllabus

Class 8 English Grammar Statistics for Economics Technology Notes SSC CGL Practice

Complete Study Economics Economy Notes Papers

Material Ethics Notes

Previous Year Papers

Colleges Companies Preparation Exams More Tutorials Write & Earn

Indian Colleges IT Companies Corner JEE Mains So ware Write an Article


Admission & So ware Company Wise JEE Advanced Development Improve an Article
Campus Experiences Development Preparation So ware Testing
GATE CS Pick Topics to Write
Top Engineering Companies Preparation for SDE Product
NEET Share your
Colleges Artificial Management
Experienced UGC NET Experiences
Top BCA Colleges Intelligence(AI) Interviews SAP Internships
Top MBA Colleges Companies
Internship SEO
Top Architecture CyberSecurity Interviews Linux
College Companies
Competitive Excel
Choose College For Service Based Programming
Graduation Companies
Aptitude
Product Based Preparation
Companies
Puzzles
PSUs for CS
Engineers

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

You might also like