Skip to lesson

Why we measure speed

Two Java methods can return the exact same answer on a 5-element test case, yet one finishes in a millisecond on real data while the other freezes the server for ten minutes. Measuring how work grows with the input size lets you spot slow code before it ever runs.

Same answer, very different speed

An algorithm is a finite list of clear steps that solves a problem. Two algorithms can give the same answer but take very different time.

Two methods can add the numbers from 1 to n and give the same answer. Method A loops n times; Method B uses one formula. The code below counts their steps.

When n = 10, both methods finish before you can blink. When n = 1,000,000,000 (one billion), Method A performs one billion additions, while Method B still performs just one multiplication, one addition, and one division.

Example 1 · Brute force: add 1 to n with a loop (O(n) time, O(1) space)

SumLoopDemo.javaJava
public class SumLoopDemo {    // Method A: loop adds 1..n one by one (n steps)    public static long sumWithLoop(int n) {        long sum = 0;        int steps = 0;        for (int i = 1; i <= n; i++) {            sum += i;            steps++;        }        System.out.println("Loop (n=" + n + ") -> sum=" + sum + ", steps=" + steps);        return sum;    }
    public static void main(String[] args) {        sumWithLoop(1000);    }}
Output
Loop (n=1000) -> sum=500500, steps=1000

What this code does

  • The loop adds the numbers one at a time, so it takes 1,000 steps for n = 1,000.
  • If n were 1,000,000,000 it would run a billion iterations.

Example 2 · Optimal: use the formula n(n + 1) / 2 (O(1) time, O(1) space)

SumFormulaDemo.javaJava
public class SumFormulaDemo {    // Method B: Gauss formula computes the exact same answer in 1 step    public static long sumWithFormula(int n) {        long sum = (long) n * (n + 1) / 2;        int steps = 1;        System.out.println("Formula (n=" + n + ") -> sum=" + sum + ", steps=" + steps);        return sum;    }
    public static void main(String[] args) {        sumWithFormula(1000);    }}
Output
Formula (n=1000) -> sum=500500, steps=1

What this code does

  • The answer is the same, 500500, but it takes one step however large n is.
  • It is faster because pairing 1 with n, 2 with n - 1 and so on gives n / 2 pairs that each add up to n + 1, so no loop is needed.

Suppose you want to add the numbers from 1 to n. Method A runs a for loop that adds 1 + 2 + 3 + ... + n one number at a time. Method B uses the mathematical formula n * (n + 1) / 2.

  • Correctness is only half the job; your solution must also finish within the allowed time.
  • Small sample tests hide speed problems because modern CPUs can do thousands of steps in a microsecond.
  • The gap between a slow method and a fast method grows wider as the input gets larger.
In coding rounds, 'Time Limit Exceeded' (TLE) means your logic may be right, but your method took too many steps on a large test case.

Counting steps instead of seconds

You might wonder why we do not just time a method with System.nanoTime() and report that it took 4 milliseconds. The problem is that wall-clock time depends on the machine, not just the algorithm.

Example 3 · Brute force: compare every pair for a duplicate (O(n²) time, O(1) space)

DuplicateNestedDemo.javaJava
public class DuplicateNestedDemo {    // Count comparisons in a nested duplicate check    public static int nestedStepCount(int[] nums) {        int steps = 0;        for (int i = 0; i < nums.length; i++) {            for (int j = i + 1; j < nums.length; j++) {                steps++;                if (nums[i] == nums[j]) {                    return steps;                }            }        }        return steps;    }
    public static void main(String[] args) {        // 200 distinct numbers (worst case: no duplicates)        int[] data = new int[200];        for (int i = 0; i < data.length; i++) {            data[i] = i;        }        System.out.println("Nested steps (n=200) : " + nestedStepCount(data));    }}
Output
Nested steps (n=200) : 19900

What this code does

  • The method compares every number with every number after it, so 200 numbers need 19,900 comparisons.
  • The work grows with n × n, which is why nested loops explode on large input.

Example 4 · Optimal: remember seen numbers in a HashSet (O(n) time, O(n) space)

DuplicateHashSetDemo.javaJava
import java.util.HashSet;import java.util.Set;
public class DuplicateHashSetDemo {    // Count lookups in a HashSet duplicate check    public static int hashSetStepCount(int[] nums) {        Set<Integer> seen = new HashSet<>();        int steps = 0;        for (int n : nums) {            steps++;            if (!seen.add(n)) {                return steps;            }        }        return steps;    }
    public static void main(String[] args) {        int[] data = new int[200];        for (int i = 0; i < data.length; i++) {            data[i] = i;        }        System.out.println("HashSet steps (n=200): " + hashSetStepCount(data));    }}
Output
HashSet steps (n=200): 200

What this code does

  • Each number is looked up once in the set, so 200 numbers need 200 steps, nearly 100 times fewer than the nested loop.
  • It is faster because the set answers 'have I seen this?' directly instead of rescanning the array. The price is O(n) extra memory for the set.
  • Stopwatch time changes with CPU speed, battery mode, other running programs, and JVM warm-up.
  • Step count depends only on your algorithm and the input data.
  • Counting steps lets two engineers on completely different laptops agree on which algorithm scales better.

The exact same Java code will run at different speeds on a gaming desktop, a budget laptop, or a busy cloud container, and even on the same machine depending on background apps and JIT compilation (when the JVM warms up and compiles hot bytecode into native machine code). Instead of counting seconds, we count elementary steps—basic operations like comparisons, arithmetic, and array accesses whose each take a tiny, roughly fixed amount of work.

Input size n

To describe how step counts grow, we express the number of steps using a variable called the input size, usually written as n. What n represents depends on what your method receives.

Example 5 · Identifying input size when there are two separate arrays

TwoInputSizesDemo.javaJava
import java.util.HashSet;import java.util.Set;
public class TwoInputSizesDemo {    // Input has TWO sizes: n = a.length, m = b.length    // Nested scan does n * m comparisons    public static int countCommonSlow(int[] a, int[] b) {        int steps = 0;        int common = 0;        for (int x : a) {            for (int y : b) {                steps++;                if (x == y) {                    common++;                }            }        }        System.out.println("Slow common=" + common + ", steps=" + steps);        return common;    }
    // HashSet scan does n + m steps    public static int countCommonFast(int[] a, int[] b) {        Set<Integer> setA = new HashSet<>();        int steps = 0;        for (int x : a) {            setA.add(x);            steps++;        }        int common = 0;        for (int y : b) {            steps++;            if (setA.contains(y)) {                common++;            }        }        System.out.println("Fast common=" + common + ", steps=" + steps);        return common;    }
    public static void main(String[] args) {        int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // n = 10        int[] b = {2, 4, 6, 8, 10, 12, 14, 16};     // m = 8        countCommonSlow(a, b);        countCommonFast(a, b);    }}
Output
Slow common=5, steps=80
Fast common=5, steps=18

What this code does

  • With n = 10 and m = 8, the nested loop performs n * m = 80 steps, whereas the HashSet version performs n + m = 18 steps.
  • When a and b have different lengths, writing n + m instead of 2n keeps your analysis accurate.
  • Array or List: n is the number of elements (arr.length or list.size()).
  • String: n is the number of characters (s.length()).
  • Numeric range 1..N: n is the numeric value N.
  • Two inputs: use both sizes (such as n and m) instead of assuming they are equal.

For an array int[] nums, n is nums.length. For a String s, n is s.length(). For a loop that counts up to a number limit, n is the value of limit itself. When a problem has two independent inputs—such as two arrays of lengths n and m, or a grid with R rows and C columns—we keep both variables in the step count.

Real cost of slow code: timeouts, slow pages, server bills

Measuring step growth is not just an academic exercise for placement tests. In production backend systems, the difference between n steps and n² steps directly affects users and company budgets.

If an API endpoint checks 20,000 orders using a nested loop (400,000,000 checks per request), a handful of concurrent users will peg the server's CPU at 100%, trigger HTTP 504 gateway timeouts, and force the company to rent more cloud servers. Replacing that nested loop with a hash lookup drops the work to 20,000 checks and cuts the CPU bill to a fraction.

  • Coding assessments: large hidden tests fail with Time Limit Exceeded (usually around 1–2 seconds).
  • Web & mobile apps: slow endpoints make pages feel laggy and cause request timeouts.
  • Cloud infrastructure: wasted CPU cycles mean paying for extra server instances 24/7.

Next step

Check your understanding

10 quick questions