Skip to the page

Basics for coding rounds · core

cin, cout, fast input and time limits

Coding tests read large inputs and have a time limit. Know how cin and cout behave, the two lines that make them fast, and how to check your idea against the limits before you write code.

The notes

What you must know

  • cin >> x skips spaces and newlines and reads one value. getline(cin, s) reads a whole line, spaces included.
  • After cin >> n, the newline stays in the input, so the next getline reads an empty line. Fix: cin >> ws (or cin.ignore) before getline.
  • ios::sync_with_stdio(false); lets the C++ streams buffer on their own, which is much faster. Call it first in main, before any input or output.
  • After sync is off, do not mix printf or scanf with cout or cin: the output can come out in the wrong order.
  • cin.tie(nullptr); stops cin from flushing cout before every read. By default cin is tied to cout.
  • endl writes a newline and flushes the stream. '\n' only writes the newline. Many endl in a big output loop can make a correct solution too slow.
  • Rule of thumb: about 10^8 simple steps per second. Read the constraints first: for n = 10^5, O(n log n) is fine, but O(n^2) is 10^10 steps and too slow.
  • Loop costs: two nested loops of n are O(n^2), even when the inner one runs only i times; a loop where i doubles is O(log n); two loops one after the other are O(n + m), not O(n x m).

The red pen

Common traps: mistake → fix

  • Mistake: endl and '\n' are the same

    Fix: endl also flushes, which is slow inside a loop.

  • Mistake: The judge machine is slow

    Fix: check the step count against the constraints first.

  • Mistake: Fast input fixes any Time Limit Exceeded

    Fix: it helps only with large input or output; an O(n^2) idea is still too slow.

  • Mistake: printf and cout mix freely after sync_with_stdio(false)

    Fix: the output can come out of order.

Easy to hard

Questions interviewers ask, easy to hard

  1. What do ios::sync_with_stdio(false) and cin.tie(nullptr) do?
  2. Why is endl slower than '\n'?
  3. You read n with cin and then a name with getline, and the name is always empty. Why?
  4. What is the time complexity of these loops: nested n by n, nested with j < i, i doubling, and two loops one after the other?
  5. Your solution passes the samples and then gets Time Limit Exceeded. n is 2 lakh. What do you check?

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