Skip to the page

Programming basics · core

Time complexity and coding-test problems

Know how to count the cost of loops and how to fix Time Limit Exceeded or a crash on a large test.

The notes

What you must know

  • Big O says how steps grow with the input, ignoring constants. It is usually quoted for the worst case.
  • n x n loops: O(n^2). A loop where the inner runs 0 + 1 + ... + (n-1) times is n(n-1)/2, still O(n^2).
  • A loop where i doubles each time is O(log n). A loop of n with an inner log n loop is O(n log n). Two loops one after the other (not inside) are O(n + m), not O(n x m).
  • Rule of thumb: about 10^8 simple steps per second in C++ or Java; fewer in Python. n = 10^5 with n^2 is 10^10 steps: too slow.
  • Time Limit Exceeded: read the constraints first. Change the approach, for example a hash map counting seen values gives O(n) for pair problems. Sorting plus two pointers is O(n log n).
  • Slow input also matters: use BufferedReader in Java, and ios::sync_with_stdio(false) and cin.tie(nullptr) in C++.
  • Segmentation fault only on a big test: an array too small for the constraints, or recursion as deep as n. Build with -g -fsanitize=address,undefined or use gdb to find the line.
  • Reverse a string without library functions: swap characters from both ends with two indexes until they meet, O(n) time and O(1) extra space; handle empty and one-letter strings.

The red pen

Common traps: mistake → fix

  • Mistake: Tune the nested loop to fix TLE

    Fix: change the approach.

  • Mistake: The judge machine is slow

    Fix: check the complexity against the constraints.

  • Mistake: A bigger array like 10^9 fixes the crash

    Fix: it can use too much memory; size from the constraints.

  • Mistake: Two loops one after another are O(n x m)

    Fix: they are O(n + m).

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the time complexity of these five loops?
  2. Your solution passes the samples and then gets Time Limit Exceeded. What do you do?
  3. It crashes with a segmentation fault only on the big test. What do you check?
  4. Reverse a string without library functions.

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview