Online coding assessments: format and Java setup
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Your code passes the sample, then the platform says "wrong answer" or "time limit exceeded" on tests you cannot see. Coding rounds are scored by a program, not a reader, so format, input handling and speed matter as much as the idea.
Anatomy of a coding problem
A judge is the program on a coding platform that runs your code on test cases and compares your output with the expected output. Nobody reads your code at this stage.
Every problem has the same parts: a statement, input and output formats, constraints and samples. Here is a problem in that shape, used through the rest of this lesson.
Order totalsShopLite received n orders today. Print the total sales and the largest order.Input: line 1: n line 2: n integers a1 ... an (order amounts)Output: line 1: total line 2: largest orderConstraints: 1 <= n <= 100000, 1 <= ai <= 1000000000Sample input: Sample output:5 60001200 950 1800 700 1350 1800Hidden test cases are the many inputs you never see, including edge cases and very large inputs. Passing the samples only proves your program works for the samples. The constraints (here 1 ≤ n ≤ 10⁵) tell you how large those hidden inputs can get.
Reading input in Java: Scanner and BufferedReader
BufferedReader reads a whole line quickly, and StringTokenizer splits it into space-separated pieces that you convert with Integer.parseInt or Long.parseLong. For 10⁵ numbers or more it is the usual safe choice, because Scanner is slow.
Below, the same problem is solved twice: first with Scanner, then with BufferedReader and StringTokenizer.
Example 1 · Solution with Scanner
import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long total = 0; long highest = 0; for (int i = 0; i < n; i++) { long amount = sc.nextLong(); total += amount; highest = Math.max(highest, amount); } System.out.println(total); System.out.println(highest); }}6000 1800
What this code does
- Run it and type the sample input (5, then the five order amounts), or pipe it in from a file:
java Main < input.txt. It prints exactly two lines and nothing else. totalis along: 10⁵ order amounts of up to 10⁹ each can reach 10¹⁴, far above theintlimit.
Example 2 · The same solution with BufferedReader and StringTokenizer
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)); int n = Integer.parseInt(br.readLine().trim()); StringTokenizer st = new StringTokenizer(br.readLine()); long total = 0; long highest = 0; for (int i = 0; i < n; i++) { long amount = Long.parseLong(st.nextToken()); total += amount; highest = Math.max(highest, amount); } System.out.println(total); System.out.println(highest); }}6000 1800
What this code does
readLine()reads one full line;trim()removes stray spaces around n.StringTokenizerthen hands out the order amounts one by one from the second line.- This version reads 10⁵ or more numbers much faster than
Scanner, which is why it is the usual template for coding rounds.
Most platforms expect one file with one public class, often named Main. Keep the class name from the template and add no package line unless the template has one.
- Add
throws IOExceptiontomain, or catch it. - Use
longwhen a sum or product can pass about 2.1 × 10⁹, theintlimit.
Fix the error
Fix the fast-input code
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
Read the number of orders with BufferedReader.
Error
Main.java:6: error: unreported exception IOException; must be caught or declared to be thrown
int n = Integer.parseInt(br.readLine().trim());
^Printing exactly the expected output
The output format is the part of the problem that says exactly what to print and in what layout. The judge compares your output with the expected one, often character by character or line by line.
Extra text such as a prompt makes a right number wrong. The examples below show outputs with the same numbers, only one of which matches, and a faster way to print many lines.
Example 3 · Extra text makes a right answer wrong
public class OutputFormatDemo { public static void main(String[] args) { int[] marks = { 78, 91, 66 }; String expected = "78 91 66";
String withPrompt = "Marks are: 78 91 66"; StringBuilder loop = new StringBuilder(); for (int m : marks) { loop.append(m).append(' '); // leaves a space at the end } String joined = String.join(" ", "78", "91", "66");
System.out.println("[" + withPrompt + "] matches: " + withPrompt.equals(expected)); System.out.println("[" + loop + "] matches: " + loop.toString().equals(expected)); System.out.println("[" + joined + "] matches: " + joined.equals(expected)); }}[Marks are: 78 91 66] matches: false [78 91 66 ] matches: false [78 91 66] matches: true
What this code does
- The brackets show exactly what was printed. The label and the trailing space both break an exact match, even though the numbers are right.
- Some judges ignore the trailing space, but the label always fails. Print only what the output format asks for.
Example 4 · Fast output with one StringBuilder
public class FastOutputDemo { public static void main(String[] args) { int n = 5; StringBuilder out = new StringBuilder(); for (int i = 1; i <= n; i++) { out.append(i).append(' ').append((long) i * i).append('\n'); } System.out.print(out); }}1 1 2 4 3 9 4 16 5 25
What this code does
- Every line is added to one
StringBuilder, andSystem.out.print(out)writes it all at once at the end. With 10⁵ lines this is much faster than 10⁵ separateprintlncalls. - The
(long)cast keepsi * isafe for largei; without it,i * ioverflowsintonceipasses 46,340.
Many judges ignore a trailing space or a final newline, but not all, so match the format exactly. For large output, printing thousands of lines one by one with System.out.println can be slow. Build the output in a StringBuilder and print it once at the end.
Find the bug
Find the output bug
Each program prints the right numbers but gets wrong answer. Tap the line to fix.
Expected output is just 6000.
Round 1 of 3Verdicts: accepted, wrong answer, time limit, errors
A verdict is the judge's result for one test case, such as Accepted, Wrong answer, Time limit exceeded, Runtime error or Compilation error.
The mini judge below runs a buggy and a fixed solution on five hidden-style tests and reports a partial score.
Example 5 · A mini judge: wrong answer on one hidden test
import java.util.Scanner;
public class MiniJudgeDemo { static String solveBuggy(String input) { Scanner sc = new Scanner(input); int n = sc.nextInt(); int total = 0, highest = 0; // bug: int total for (int i = 0; i < n; i++) { int amount = sc.nextInt(); total += amount; highest = Math.max(highest, amount); } return total + "\n" + highest; }
static String solveFixed(String input) { Scanner sc = new Scanner(input); int n = sc.nextInt(); long total = 0, highest = 0; for (int i = 0; i < n; i++) { long amount = sc.nextLong(); total += amount; highest = Math.max(highest, amount); } return total + "\n" + highest; }
public static void main(String[] args) { String[] inputs = { "5\n1200 950 1800 700 1350", "1\n5", "3\n7 7 7", "4\n10 20 30 40", "3\n1000000000 1000000000 1000000000" }; String[] expected = { "6000\n1800", "5\n5", "21\n7", "100\n40", "3000000000\n1000000000" };
System.out.println("Buggy solution:"); int passed = 0; for (int t = 0; t < inputs.length; t++) { String got = solveBuggy(inputs[t]); if (got.equals(expected[t])) { passed++; System.out.println("Test " + (t + 1) + ": passed"); } else { System.out.println("Test " + (t + 1) + ": wrong answer (expected total " + expected[t].split("\n")[0] + ", got " + got.split("\n")[0] + ")"); } } System.out.println("Passed " + passed + " of " + inputs.length + " -> partial score " + passed * 100 / inputs.length + "%");
passed = 0; for (int t = 0; t < inputs.length; t++) { if (solveFixed(inputs[t]).equals(expected[t])) passed++; } System.out.println("Fixed solution: passed " + passed + " of " + inputs.length); }}Buggy solution: Test 1: passed Test 2: passed Test 3: passed Test 4: passed Test 5: wrong answer (expected total 3000000000, got -1294967296) Passed 4 of 5 -> partial score 80% Fixed solution: passed 5 of 5
What this code does
- The buggy version passes the sample and small tests, so it looks right. The hidden test with three order amounts of 10⁹ overflows
intand wraps around to a negative number: a wrong answer verdict. - Partial scoring gave 80% even with the bug. Changing
inttolongfixes it; this is the most common wrong-answer cause in fresher rounds.
Common verdicts:
- Accepted: correct output within the time limit.
- Wrong answer: the output differs. Check edge cases, overflow and format.
- Time limit exceeded (TLE): too slow. Use a better algorithm or faster input and output.
- Runtime error: the program crashed, for example with
ArrayIndexOutOfBoundsExceptionorNumberFormatException. - Compilation error: the code did not compile.
Many assessments use partial scoring: marks for each hidden test you pass. A simple solution that passes 6 of 10 tests is worth far more than a clever one that does not compile. Revise: Overflow and big numbers (opens in a new tab)
Order of execution
Debug a wrong answer
After a wrong answer verdict, put your checks in the order that finds most bugs fastest.
Reading constraints to pick the complexity
Constraints are the limits the problem promises for its input, such as 1 ≤ n ≤ 10⁵ and values up to 10⁹. They tell you how fast your solution must be.
A judge runs about 10⁷ to 10⁸ simple operations per second, and the time limit is usually 1 to 2 seconds. The example below estimates steps for n = 10⁵.
Example 6 · Estimating steps from the constraints
public class ComplexityEstimateDemo { public static void main(String[] args) { long n = 100_000; long pairs = n * (n - 1) / 2; // O(n^2): every pair double nLogN = n * (Math.log(n) / Math.log(2)); // O(n log n): sorting double opsPerSecond = 1e8; // rough estimate
System.out.println("n = " + n); System.out.printf("O(n^2) pairs: %d steps, about %.1f s%n", pairs, pairs / opsPerSecond); System.out.printf("O(n log n): %.0f steps, about %.3f s%n", nLogN, nLogN / opsPerSecond); System.out.printf("O(n): %d steps, about %.3f s%n", n, n / opsPerSecond); }}n = 100000 O(n^2) pairs: 4999950000 steps, about 50.0 s O(n log n): 1660964 steps, about 0.017 s O(n): 100000 steps, about 0.001 s
What this code does
- Checking every pair of 10⁵ items is about 5 × 10⁹ steps: around 50 seconds at a rough 10⁸ steps per second, far over a 1 to 2 second limit. That is a time limit exceeded verdict.
- Sorting-based O(n log n) needs about 1.7 million steps and O(n) only 10⁵, both well inside the limit. Read the constraints first and choose the approach before you type.
Real speed depends on the platform and the code, so treat this as an estimate. For n up to 10⁵, O(n²) means about 10¹⁰ steps, far too slow; O(n log n) or O(n) is needed.
- n ≤ 20: O(2ⁿ) or O(n!) can pass.
- n ≤ 1000 to 5000: O(n²) is usually fine.
- n ≤ 10⁵ to 10⁶: O(n log n) or O(n).
- n up to 10⁹ or more: O(log n) or a formula.
Revise: From constraints to a target complexity (opens in a new tab)
Predict the output
Predict the step count
Read each program and pick what it prints.
Round 1 of 2
Next step
Check your understanding
12 quick questions