Skip to content

Expert · Competitive programming, interviews and careers · topic 38 of 42 · 30 min

Competitive programming with C++: setup and time limits

Explanation

Contest sites (Codeforces, CodeChef, AtCoder, LeetCode, CSES) give a problem, input limits and a time limit, usually 1–2 seconds. C++ is popular because it is fast and the STL has ready-made data structures. Read the limits first: they tell you which time complexity your solution needs.

What competitive programming is

In competitive programming (CP) you solve well-defined problems by writing a program that reads input and prints output. An online judge runs your program on hidden tests and replies with a verdict: Accepted (AC), Wrong Answer (WA), Time Limit Exceeded (TLE), Runtime Error (RE) or Memory Limit Exceeded (MLE). Many Indian companies use the same style of problems in online assessments, so CP practice doubles as placement preparation.

Where to practise

SiteGood for
CSES Problem Set (cses.fi)A classic, well-ordered list of a few hundred standard problems
CodeforcesFrequent rated contests, huge problem archive with ratings
CodeChefIndian platform with Starters contests and learning paths
AtCoderClean problems; Beginner Contests are excellent for learning
LeetCodeInterview-style problems; function-based, not full programs
ICPCThe team contest for college students (regional rounds held in India)

A contest template

cpp
#include <bits/stdc++.h>     // GCC-only header that includes the whole standard library
using namespace std;
using ll = long long;

void solve() {
    int n;
    cin >> n;
    vector<ll> a(n);
    for (auto& x : a) cin >> x;
    cout << accumulate(a.begin(), a.end(), 0LL) << '\n';
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t = 1;
    cin >> t;                    // many problems have several test cases
    while (t--) solve();
}
Fast I/O, long long by default for sums, and a solve() per test case.
Careful: #include <bits/stdc++.h> and "using namespace std;" are fine in contests to save typing, but they are NOT for real projects. bits/stdc++.h only exists with GCC's library (it fails with MSVC and with Clang on macOS by default) and slows compilation.

Time limit maths

A rough rule: a judge machine does around 10^8 simple operations per second in C++ (it varies; treat it as an estimate). So from the input size n you can guess the complexity you need:

n up toComplexity that usually passesTypical idea
10–11O(n!)try all permutations
20–25O(2^n)try all subsets, bitmasks
500O(n³)triple loops, Floyd–Warshall
5,000O(n²)double loops, simple DP
2 × 10^5 to 10^6O(n log n) or O(n)sorting, binary search, prefix sums, two pointers
10^9 and moreO(log n) or O(1)maths, binary search on the answer
Think of it like this: The constraints are like the size of a crowd you must count. For 20 people you can count every possible group photo. For a stadium of 1,00,000 you must count smartly, row by row, or the match ends before you finish.

A good practice routine

  1. Read the whole statement and the limits before coding. Work out the needed complexity.
  2. Solve the sample by hand to make sure you understand it.
  3. Think of edge cases: n = 1, all equal values, the largest values (overflow?), negative numbers.
  4. Code, test on samples, then on your own tricky cases.
  5. After the contest, read the editorial for problems you could not solve, and solve them again ("upsolving"). This is where most learning happens.
Tip: Consistency beats bursts: one or two problems a day, slightly above your comfort level, for months. Track problems you failed and why.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Competitive programming with C++: setup and time limits · 1/6

Competitive programming

Competitive programming means solving exact problems against hidden tests and a time limit.

Prefer a video by a teacher? Find free videos on “competitive programming c++ for beginners template time complexity” on YouTube ↗

In real life: An online assessment for a placement

Many companies hiring in India start with a 60–90 minute online test on platforms such as HackerRank or HackerEarth: two or three coding problems with hidden test cases. A student who has practised on CSES and Codeforces recognises the patterns, checks the limits (n ≤ 2 × 10^5 means O(n log n)), uses long long for sums and fast I/O, and finishes with time to test edge cases.

cpp
// Constraint check before coding:
// n ≤ 200000, values ≤ 10^9  →  sums up to 2 × 10^14  →  use long long
// O(n²) = 4 × 10^10 operations → too slow; need O(n log n) or O(n)
long long total = 0;
for (int x : a) total += x;     // total is long long, so no overflow
Thirty seconds of limit maths saves a Wrong Answer and a TLE.

Practice (0/4 done)

Task 1 · Question

n ≤ 2 × 10^5 and the time limit is 1 second. Which complexity is safe?

Task 2 · Question

Your solution is correct on samples but the judge says TLE. What does that mean?

Task 3 · Question

Why might #include <bits/stdc++.h> fail on a friend's Mac?

Task 4 · Practice

Create accounts on CSES and Codeforces (or CodeChef). Solve the first 5 problems of the CSES "Introductory Problems" section in C++ using a template with fast I/O. For each, write down the constraint, the complexity you chose and one edge case you tested.

Quick quiz

Question 1

1.What is "upsolving"?

Question 2

2.n ≤ 20 usually hints at which approach?

Question 3

3.What does Wrong Answer on test 7 most often point to?

Question 4

4.About how many simple operations per second should you assume for C++ on a judge?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is "upsolving"?

Answer: Solving the problems you could not solve, after the contest, using the editorial if needed

Upsolving is where most improvement comes from.

n ≤ 20 usually hints at which approach?

Answer: Trying all subsets (O(2^n))

2^20 ≈ 10^6 subsets is fast enough.

What does Wrong Answer on test 7 most often point to?

Answer: A logic bug or a missed edge case such as overflow

Check edge cases, overflow and the exact output format.

About how many simple operations per second should you assume for C++ on a judge?

Answer: 10^8

A common rule of thumb is about 10^8, which helps estimate whether an approach fits.

In the routine, what should you write before trying to optimise?Related

Answer: A simple brute-force idea and its cost

A correct brute force gives you a baseline and often shows which repeated work to remove.

From What DSA is, and how to learn it

What makes dynamic programming faster than plain recursion for problems like Fibonacci?Related

Answer: Each sub-problem's answer is stored and reused instead of recomputed

Overlapping sub-problems are solved once.

From Core DSA patterns in C++

What does a C++ compiler produce from your source code?Related

Answer: Machine code in an executable file

The compiler translates C++ into machine code, saved as a program you can run directly.

From What C++ is and how compiling works

Box b(3.5); compiles in C++17 because of…Related

Answer: class template argument deduction (CTAD)

CTAD deduces Box<double> from the constructor argument.

From Templates: code for any type

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Competitive programming, interviews and careers” before its exam: Core DSA patterns in C++, Classic C++ pitfalls in contests and coding rounds, C++ interview questions and how to answer them, Careers with C++ and your next steps.
  2. Module 10 exam: Contests, interviews and careers · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. 42 topics left in the course before the final exam.

← Previous: Building real projects: CMake, warnings, debuggers and sanitizers