Java Generics to Code Efficiently in Competitive Programming Last Updated : 10 May, 2022 Comments Improve Suggest changes Like Article Like Report Templates are the foundation of generic programming, which involve writing code in a way that is independent of any particular type. These powerful tools can be used for writing our code effectively. Some cool tricks that may be used in Competitive Programming are given as follows: Fast Input/Output: This uses the time advantage of BufferedReader and StringTokenizer and the advantage of user-defined methods for less typing and therefore a faster input altogether. Below is the code to find the sum of N integers using fast reader and writer. Java // Java program to illustrate the fast // input output import java.io.*; import java.util.StringTokenizer; public class GFG { // Driver Code public static void main(String[] args) throws IOException { // Initialize the reader FastReader reader = new FastReader(); // Initialize the writer FastWriter writer = new FastWriter(); // Your Code here // Reads a single integer int n = reader.readSingleInt(); // Reads a array of N number // in a line int a[] = reader.readIntArray(n); // Prints a string writer.writeString("SUM OF :"); // Print the array of number // with spaces writer.writeIntArrayWithSpaces(a); int sum = 0; for (int i = 0; i < n; i++) { sum += a[i]; } // Prints a single number writer.writeSingleInteger(sum); } // Fast Reader Class public static class FastReader { // Reader object BufferedReader reader; // Constructor public FastReader() { // Initialize the reader reader = new BufferedReader( new InputStreamReader( System.in)); } // String tokenizer StringTokenizer tokenizer; // Function to read integer public int readSingleInt() throws IOException { return Integer.parseInt( reader.readLine()); } // Function to read a single long public long readSingleLong() throws IOException { return Long.parseLong( reader.readLine()); } // Function to read a array of // numsInts integers in 1 line public int[] readIntArray(int numInts) throws IOException { int[] nums = new int[numInts]; tokenizer = new StringTokenizer( reader.readLine()); // Input Numbers for (int i = 0; i < numInts; i++) { nums[i] = Integer.parseInt( tokenizer.nextToken()); } return nums; } // Function to read string public String readString() throws IOException { return reader.readLine(); } } // Fast Writer Class public static class FastWriter { // Writer object BufferedWriter writer; // Constructor public FastWriter() { // Initialize the writer writer = new BufferedWriter( new OutputStreamWriter( System.out)); } // Function to write single integer public void writeSingleInteger(int i) throws IOException { writer.write(Integer.toString(i)); writer.newLine(); writer.flush(); } // Function to write a single long public void writeSingleLong(long i) throws IOException { writer.write(Long.toString(i)); writer.newLine(); writer.flush(); } // Function to write a Integer // of array with spaces in 1 line public void writeIntArrayWithSpaces( int[] nums) throws IOException { for (int i = 0; i < nums.length; i++) { writer.write(nums[i] + " "); } writer.newLine(); writer.flush(); } // Function to write a Integer // of array without spaces // in 1 line public void writeIntArrayWithoutSpaces(int[] nums) throws IOException { for (int i = 0; i < nums.length; i++) { writer.write( Integer.toString( nums[i])); } writer.newLine(); writer.flush(); } // Function to write a String public void writeString(String s) throws IOException { writer.write(s); writer.newLine(); writer.flush(); } } }  In order to change the input and output stream based on the environment to text files or to standard input as usually done while using sublime text or other IDEs use the below code as template of FastIO. Java // Java program to illustrate the // fast input output import java.io.*; import java.util.StringTokenizer; public class GFG { public // Driver Code static void main(String[] args) throws IOException { // Initialize the reader FastReader reader = new FastReader(); // Initialize the writer FastWriter writer = new FastWriter(); // Your Code here } // Fast Reader Class public static class FastReader { // Reader object BufferedReader reader; // Constructor public FastReader() { // Initialize the reader reader = new BufferedReader( new InputStreamReader( System.in)); if (System.getProperty( "ONLINE_JUDGE") == null) { try { reader = new BufferedReader( new InputStreamReader( new FileInputStream( "input.txt"))); } catch (Exception e) { } } } // String tokenizer StringTokenizer tokenizer; // Function to read a // single integer public int readSingleInt() throws IOException { return Integer.parseInt( reader.readLine()); } // Function to read a // single long public long readSingleLong() throws IOException { return Long.parseLong( reader.readLine()); } // Function to read a array // of numsInts integers // in one line public int[] readIntArray(int numInts) throws IOException { int[] nums = new int[numInts]; tokenizer = new StringTokenizer( reader.readLine()); for (int i = 0; i < numInts; i++) { nums[i] = Integer.parseInt( tokenizer.nextToken()); } return nums; } // Function to read string public String readString() throws IOException { return reader.readLine(); } } // Fast Writer Class public static class FastWriter { // Writer object BufferedWriter writer; // Constructor public FastWriter() { // Initialize the writer writer = new BufferedWriter( new OutputStreamWriter( System.out)); if (System.getProperty( "ONLINE_JUDGE") == null) { try { writer = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( "output.txt"))); } catch (Exception e) { } } } // Function to write the // single integer public void writeSingleInteger(int i) throws IOException { writer.write(Integer.toString(i)); writer.newLine(); writer.flush(); } // Function to write single long public void writeSingleLong(long i) throws IOException { writer.write(Long.toString(i)); writer.newLine(); writer.flush(); } // Function to write a Integer of // array with spaces in one line public void writeIntArrayWithSpaces(int[] nums) throws IOException { for (int i = 0; i < nums.length; i++) { writer.write(nums[i] + " "); } writer.newLine(); writer.flush(); } // Function to write Integer of // array without spaces in 1 line public void writeIntArrayWithoutSpaces(int[] nums) throws IOException { for (int i = 0; i < nums.length; i++) { writer.write( Integer.toString( nums[i])); } writer.newLine(); writer.flush(); } // Function to write String public void writeString(String s) throws IOException { writer.write(s); writer.newLine(); writer.flush(); } } } Note: For Information above Fast Input/Output in Java please refer to this post. Functions commonly used in Competitive Programming: Below are the functions that are commonly used during competitive programming, one can include them in the code to avoid wastage of time implementing it during the contest. Pairs in Java: Pairs are commonly used in competitive programming. It is an easy way to use pairs in JAVA. Below is the implementation of the same: Java // Java program to illustrate the // use Pairs import java.io.*; class GFG { // Driver Code public static void main(String[] args) { // Initialize a pair Pair<Integer, Integer> x = new Pair<Integer, Integer>(1, 2); // Print pair System.out.println(x.first + ", " + x.second); } // Pair class static class Pair<A, B> { A first; B second; // Constructor public Pair(A first, B second) { this.first = first; this.second = second; } } } Fast Exponential using mod: Java // Function to find x ^ n using p as mod static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } nCr using Fermat Little Theorem: Java // Function to find x ^ n using p as mod static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p static long modInverse(long n, long p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static long nCrModPFermat(int n, int r, long p) { // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r long[] fac = new long[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } Binomial Coefficient: Binomial coefficient is mostly used to find the value of [n * (N - 1) *---* (N - K + 1)] / [K * (K - 1) *----* 1]). Below is the program to implement the same: Java // Function to implement the // binomial coefficient static long binomialCoeff(long n, long k, long MOD) { long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Find the value of // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); res %= MOD; } // Return the result return res; } Modular Arithmetic: Java const int mod = 1000000007; // Function to implement the modular // arithmetic addition private static long modular_add(long a, long b) { return ((a % mod) + (b % mod)) % mod; } // Function to implement the modular // arithmetic subtraction private static long modular_sub(long a, long b) { return ((a % mod) - (b % mod) + mod) % mod; } // Function to implement the modular // arithmetic multiplication private static long modular_mult(long a, long b) { return ((a % mod) * (b % mod)) % mod; } Sort an array: Java // Function to sort an integer array static void sort(int[] a) { // Stores the element in arraylist ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); // Use collection.sort() method Collections.sort(l); // Update the original array // with the sorted array elements for (int i = 0; i < a.length; i++) a[i] = l.get(i); } GCD and LCM: Java static long lcm(int a, int b) { return (a / gcd(a, b)) * b; } private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } Comment More infoAdvertise with us Next Article Java Generics to Code Efficiently in Competitive Programming U UtkarshPandey6 Follow Improve Article Tags : Misc Java Competitive Programming DSA Java-Generics Java-Competitive-Programming +2 More Practice Tags : JavaMisc Similar Reads Competitive Programming - A Complete Guide Competitive Programming is a mental sport that enables you to code a given problem under provided constraints. The purpose of this article is to guide every individual possessing a desire to excel in this sport. This article provides a detailed syllabus for Competitive Programming designed by indust 8 min read Competitive Programming (CP) Handbook with Complete Roadmap Welcome to the Competitive Programming Handbook or CP Handbook by GeeksforGeeks! This Competitive Programming Handbook is a go-to resource for individuals aiming to enhance their problem-solving skills and excel in coding competitions. This CP handbook provides a comprehensive guide, covering fundam 12 min read Mathematics for Competitive ProgrammingMust do Math for Competitive ProgrammingCompetitive Programming (CP) doesnât typically require one to know high-level calculus or some rocket science. But there are some concepts and tricks which are sufficient most of the time. You can definitely start competitive coding without any mathematical background, but maths becomes essential as 15+ min read Pigeonhole Principle for CP | Identification, Approach & ProblemsIn competitive programming, where people solve tough problems with computer code, the Pigeonhole Principle is like a secret tool. Even though it's a simple idea, it helps programmers tackle complex challenges. This article is your guide to understanding how this principle works and why it's crucial 8 min read Euler Totient for Competitive ProgrammingWhat is Euler Totient function(ETF)?Euler Totient Function or Phi-function for 'n', gives the count of integers in range '1' to 'n' that are co-prime to 'n'. It is denoted by \phi(n) .For example the below table shows the ETF value of first 15 positive integers: 3 Important Properties of Euler Totie 8 min read Mathematics for Competitive Programming Course By GeeksforGeeksMathematics forms the foundation of problem-solving in Competitive Programming (CP). Mastering key mathematical concepts is crucial for approaching algorithmic challenges effectively. If you're an aspiring competitive programmer or someone who wishes to enhance your problem-solving skills, this Math 3 min read Number Theory for CPBinary Exponentiation for Competitive ProgrammingIn competitive programming, we often need to do a lot of big number calculations fast. Binary exponentiation is like a super shortcut for doing powers and can make programs faster. This article will show you how to use this powerful trick to enhance your coding skills. Table of ContentWhat is Binary 15+ min read GCD (Greatest Common Divisor) Practice Problems for Competitive ProgrammingGCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest positive integer that divides both of the numbers.GCD of Two NumbersFastest Way to Compute GCDThe fastest way to find the Greatest Common Divisor (GCD) of two numbers is by using the Euclidean algorithm. The E 4 min read Bit Manipulation for CPBit Manipulation for Competitive ProgrammingBit manipulation is a technique in competitive programming that involves the manipulation of individual bits in binary representations of numbers. It is a valuable technique in competitive programming because it allows you to solve problems efficiently, often reducing time complexity and memory usag 15+ min read Bit Tricks for Competitive ProgrammingIn competitive programming or in general, some problems seem difficult but can be solved very easily with little concepts of bit magic. We have discussed some tricks below in the previous post.Bitwise Hacks for Competitive Programming One-Liner Hacks of Bit Manipulation:One-Liner CodeFunctionx&1 7 min read Bitwise Hacks for Competitive ProgrammingPrerequisite: It is recommended to refer Interesting facts about Bitwise Operators How to set a bit in the number 'num': If we want to set a bit at nth position in the number 'num', it can be done using the 'OR' operator( | ).  First, we left shift '1' to n position via (1<<n)Then, use the 'O 14 min read Combinatorics for CPInclusion Exclusion principle for Competitive ProgrammingWhat is the Inclusion-Exclusion Principle?The inclusion-exclusion principle is a combinatoric way of computing the size of multiple intersecting sets or the probability of complex overlapping events. Generalised Inclusion-Exclusion over Set:For 2 Intersecting Set A and B: A\bigcup B= A + B - A\bigca 5 min read Greedy for CPBinary Search on Answer Tutorial with ProblemsBinary Search on Answer is the algorithm in which we are finding our answer with the help of some particular conditions. We have given a search space in which we take an element [mid] and check its validity as our answer, if it satisfies our given condition in the problem then we store its value and 15+ min read Ternary Search for Competitive ProgrammingTernary search is a powerful algorithmic technique that plays a crucial role in competitive programming. This article explores the fundamentals of ternary search, idea behind ternary search with its use cases that will help solving complex optimization problems efficiently. Table of Content What is 8 min read Array based concepts for CPWhat are Online and Offline query-based questions in Competitive ProgrammingThe query-based questions of competitive programming are mainly of two types: Offline Query.Online Query. Offline Query An offline algorithm allows us to manipulate the data to be queried before any answer is printed. This is usually only possible when the queries do not update the original element 4 min read Precomputation Techniques for Competitive ProgrammingWhat is the Pre-Computation Technique?Precomputation refers to the process of pre-calculating and storing the results of certain computations or data structures in advance, in order to speed up the execution time of a program. This can be useful in situations where the same calculations or data stru 15+ min read PreComputation Technique on ArraysPrecomputation refers to the process of pre-calculating and storing the results of certain computations or data structures(array in this case) in advance, in order to speed up the execution time of a program. This can be useful in situations where the same calculations are needed multiple times, as 15 min read Frequency Measuring Techniques for Competitive ProgrammingMeasuring the frequency of elements in an array is a really handy skill and is required a lot of competitive coding problems. We, in a lot of problems, are required to measure the frequency of various elements like numbers, alphabets, symbols, etc. as a part of our problem. Examples: Input: arr[] = 15+ min read Dynamic Programming (DP) for CPDP on Trees for Competitive ProgrammingDynamic Programming (DP) on trees is a powerful algorithmic technique commonly used in competitive programming. It involves solving various tree-related problems by efficiently calculating and storing intermediate results to optimize time complexity. By using the tree structure, DP on trees allows p 15+ min read Dynamic Programming in Game Theory for Competitive ProgrammingIn the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive e 15+ min read Game Theory for CPInteractive Problems in Competitive ProgrammingInteractive Problems are those problems in which our solution or code interacts with the judge in real time. When we develop a solution for an Interactive Problem then the input data given to our solution may not be predetermined but is built for that problem specifically. The solution performs a se 6 min read Mastering Bracket Problems for Competitive ProgrammingBracket problems in programming typically refer to problems that involve working with parentheses, and/or braces in expressions or sequences. It typically refers to problems related to the correct and balanced usage of parentheses, and braces in expressions or code. These problems often involve chec 4 min read MEX (Minimum Excluded) in Competitive ProgrammingMEX of a sequence or an array is the smallest non-negative integer that is not present in the sequence.Note: The MEX of an array of size N cannot be greater than N since the MEX of an array is the smallest non-negative integer not present in the array and array having size N can only cover integers 15+ min read Like