BeginnerHabits & complexity

Read the constraints before you code

The input size tells you how fast your solution must be. n ≤ 10⁵ means an double loop will time out.

The idea

Online judges run roughly 10⁸ simple steps per second. Multiply out your idea's with the largest n and you know whether it can pass before writing a line.

Read it backwards too: the constraint hints at the intended solution. Tiny n invites ; huge n demands or .

Worked example

Picking an approach from n

  1. n ≤ 20 → 2²⁰ ≈ 1 million: trying every is fine.
  2. n ≤ 2,000 → n² = 4 million: a double loop is fine.
  3. n ≤ 100,000 → n² = 10 billion: too slow. Aim for O(n log n) (sort, , ) or O(n) (, ).

How to spot it

  • Every problem has at the bottom. Read them first.

Common mistakes

  • Coding the brute force for n = 10⁵ and only learning it's too slow from the judge.
  • Ignoring value ranges, which decide whether a counting array or matter.

Practise it

Go further