Java Coding Interview Template: Fast Input and Time Complexity
A Java template for coding interviews and online judges: buffered input, PrintWriter output, the time complexity each n allows, memory limits and edge cases.
- Course: Java study plan
- Module: Interview idioms
- Kind: Lesson
- Reading time: 12 min
- Runtime: OpenJDK 18
How do you choose the time complexity from the constraints?
Choose the time complexity from the largest input size in the constraints, assuming Java does about 10⁸ simple operations per second after warm-up. With a 1–2 second limit, n up to 10⁶ needs O(n log n), n up to 5 000 allows O(n²), n up to 500 allows O(n³) and n up to 25 allows O(2ⁿ). So n ≤ 10⁵ rules out O(n²): think sorting, hashing or heaps.
Lesson
Every coding round starts the same way: a problem statement, an input format, a time limit, and forty minutes. The people who do well have stopped thinking about the mechanics — how to read the input, how to print, what n ≤ 10⁵ means for the algorithm — because they carry a template and a complexity budget in their heads. This lesson gives you both, plus the edge-case checklist to run before you say "done".
The template
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = in.readLine();
if (line == null) return null; // end of input
st = new StringTokenizer(line);
}
return st.nextToken();
}
static int nextInt() throws IOException { return Integer.parseInt(next()); }
static long nextLong() throws IOException { return Long.parseLong(next()); }
public static void main(String[] args) throws IOException {
int n = nextInt();
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
out.println(solve(a));
out.flush();
}
static long solve(long[] a) { … }
}
Type it until you can produce it in ninety seconds. Notes: the null check in next() makes "read until end of input" work (while ((t = next()) != null)); everything numeric that could exceed two billion is a long from the start; solve is separate from I/O so the logic is testable and readable; and out.flush() is the last line, always.
When the problem is small, the whole-input read is even simpler: String[] tokens = new String(System.in.readAllBytes()).trim().split("\\s+"); — one allocation, then index through tokens. Watch the empty-input case: "".split("\\s+") gives [""], so check tokens[0].isEmpty().
Reading tricky formats
- Grid of characters:
char[] row = in.readLine().toCharArray()per row; neverScanner.next()(it splits on whitespace and there is none). - Line with a count then values on the same line: the tokenizer handles it; the count is just the first token.
- Unknown number of test cases: loop on
next() != null. - A line of text with spaces:
in.readLine()directly — do not mix with the tokenizer without draining it first, and rememberScanner.nextInt()leaves the newline in the buffer, so a followingnextLine()returns"". - Very large numbers:
BigInteger/BigDecimal— slow, but correct; a problem that says "up to 10¹⁸" fits inlong(9.2 × 10¹⁸); one that says "up to 100 digits" does not.
The complexity budget
A judge does roughly 10⁸ simple operations per second in Java after warm-up (a little less with heavy object allocation). With a typical 1–2 s limit:
Largest n in the statement | Complexity that fits | Typical shape |
|---|---|---|
| ≤ 12 | O(n!) | permutations, brute force |
| ≤ 25 | O(2ⁿ) | subsets, bitmask DP |
| ≤ 100 | O(n⁴) | four nested loops, small DP |
| ≤ 500 | O(n³) | Floyd–Warshall, cubic DP |
| ≤ 5 000 | O(n²) | pairwise comparison, LIS quadratic |
| ≤ 10⁶ | O(n log n) | sorting, heaps, binary search, TreeMap |
| ≤ 10⁸ | O(n) | single pass, hashing, two pointers, prefix sums |
| ≥ 10⁹ | O(log n) or O(1) | math, binary search on the answer, digit tricks |
Read the constraints before designing: n ≤ 10⁵ rules out O(n²) and tells you to think in sorting, hashing or heaps; n ≤ 20 invites a bitmask. Say your complexity out loud before coding — interviewers mark the reasoning, not just the answer.
Memory budget
A 256 MB limit fits about 60 million ints (4 bytes each), 30 million longs, or a few million small objects (16–32 bytes each plus references). A boolean[10_000_000] is 10 MB; a List<Integer> of ten million is ~200 MB and probably dead. Use primitive arrays for big data, BitSet for big boolean tables, and int[][] rather than List<List<Integer>> for grids.
Output discipline
- Buffer output (
PrintWriterorStringBuilder); flush once. - Match the format exactly: a trailing space is usually tolerated, a missing newline usually is, a stray debugging line never is.
Locale.ROOTfor decimals; print the exact number of decimals asked for with%.6f, notMath.round.- For very large answers "modulo 10⁹ + 7": reduce at every multiplication, keep intermediates in
long, andMath.floorModfor anything that could go negative.
The edge-case checklist
Before saying "done", run these in your head against your code:
- Empty input /
n = 0; single element /n = 1. - All equal elements; already sorted and reverse sorted.
- Negative numbers and zero where the statement allows them.
- Maximum sizes — does the complexity fit? Does
intoverflow anywhere (a[i] * a[j], sums,mid = (lo + hi) / 2)? - Duplicates — does your
Set/Maplogic handle them as the problem wants? - Boundaries — off-by-one in loops,
substring(i, j)end-exclusive,length - 1. - Strings: empty, one character, all the same character, case sensitivity, Unicode if the statement hints at it.
- Graphs: disconnected, self-loops, a single node, cycles when you assumed a tree.
Saying "let me check edge cases" and naming three of these is worth more than a fourth correct test.
Interview angle
- "How many operations can Java do in a second?" About 10⁸ simple ones — the number the budget table is built on.
- "n is 10⁵; what complexity do you need?" O(n log n) or better; O(n²) is 10¹⁰ — too slow.
- "Why
longhere?" Any sum or product of values up to 10⁹ overflowsint;longcovers 9 × 10¹⁸. - "Why is your I/O slow?"
Scannerand unbufferedprintln; switch to the reader template and a flushedPrintWriter. - "How do you handle end of input?"
readLine()returnsnull; thenext()helper returnsnullpast it.
Key takeaways
- Own the template: buffered reader with a refilling tokenizer,
PrintWriter,solveseparated from I/O,flushlast. - 10⁸ operations per second; map
nto the complexity that fits before designing. - Memory: primitive arrays,
BitSet,int[][]; boxed collections of millions are dead on arrival. longearly;Locale.ROOT; exact format; modulo at every step.- Run the eight-point edge-case checklist aloud.
Common questions
How many operations per second can Java do?
About 10⁸ simple operations per second after warm-up, somewhat fewer with heavy object allocation. Multiply out your algorithm's operation count at the maximum input size and compare it with that figure to see whether it fits a 1–2 second limit.
When should I use long instead of int in Java?
Whenever a sum or product can pass about 2.1 billion, the limit of int: a product of two values up to 10⁵, a sum of many large values, or a product before reducing modulo 10⁹ + 7. A long holds up to about 9.2 × 10¹⁸; beyond that, use BigInteger.
What edge cases should I check in a coding interview?
Empty input and a single element; all-equal, already sorted and reverse-sorted input; negatives and zero; maximum sizes and int overflow; duplicates; off-by-one boundaries; empty and one-character strings; and, for graphs, disconnected parts, self-loops and cycles.
How much data fits in a 256 MB memory limit in Java?
About 60 million ints or 30 million longs, but only a few million small objects. A List<Integer> of ten million elements takes around 200 MB, so use primitive arrays, BitSet and int[][] for large data instead of boxed collections.
Exercises
Read until the end
Using the template's next() helper (which returns null at end of input — no Scanner), read every integer from standard input, however many lines there are. Print count=<n> sum=<sum> min=<min> max=<max> using longs, or just count=0 when there are none. Write the answer through a flushed PrintWriter.
Example (three lines): 3 9, -2, 7 1 →
count=5 sum=18 min=-2 max=9The complexity budget
Read an integer n (1 ≤ n ≤ 10⁹). With a budget of 100000000 operations and log n taken as the bit length of n (32 - Integer.numberOfLeadingZeros(n)), print n=<n> budget=100000000 and then, for each of n log n, n^2, n^3 and 2^n in that order, either <name>: <operations> fits or <name>: too slow. Use Math.multiplyExact on longs and treat an overflow as too slow; 2^n is too slow for n ≥ 63.
Example: 20 →
n=20 budget=100000000
n log n: 100 fits
n^2: 400 fits
n^3: 8000 fits
2^n: 1048576 fitsIn this module: Interview idioms
- The interview template — input, output, limits (this lesson)
- equals, hashCode and Comparable — the contracts that make collections work
- The pitfalls that fail interviews
- The collections idiom sheet
- Writing clean solutions under time pressure
- The Java theory drill — thirty questions, thirty answers
- Final checkpoint — Interview idioms
← Checkpoint — Modern Java · equals, hashCode and Comparable — the contracts that make collections work →