Published on

Introduction

Course: Everything about Competitive Programming

Authors

Introduction

Welcome to the exciting world of competitive programming — where logic meets speed, and creativity turns into code. If you’ve ever enjoyed solving puzzles, optimizing your solutions, or racing against time to crack tricky problems, you’re going to love this.

What Is Competitive Programming?

At its heart, competitive programming is all about two things:

  • Designing algorithms – coming up with clever and efficient ways to solve problems.

  • Implementing those algorithms – turning your ideas into clean, working Python code.

You’re given a problem — maybe you need to sort numbers faster, find the shortest path in a maze, or maximize profit from limited resources. Your job? Come up with a correct, efficient, and beautiful solution.

The Art of Algorithm Design

Designing algorithms isn’t just about coding — it’s about thinking. You’ll use a mix of problem-solving, mathematical reasoning, and creativity.

For example, imagine you’re asked to find the largest sum of a subarray. A beginner might try every possible combination (which works but is slow). A more experienced programmer thinks deeper and uses Kadane’s Algorithm, which runs in linear time — lightning fast!

Here’s what it might look like in Python:

def max_subarray_sum(arr):
    max_sum = current_sum = arr[0]
    for num in arr[1:]:
        current_sum = max(num, current_sum + num)
        max_sum = max(max_sum, current_sum)
    return max_sum

That’s the beauty of algorithmic design — using smart thinking to make your code faster and cleaner.

Programming languages

So, you’ve decided to dive into the world of competitive programming — awesome! 🎉 But here’s a question that almost every beginner asks - “Which programming language should I use?”

Let’s talk about that.

Across most coding competitions — whether it’s Codeforces, LeetCode, or Google Code Jam — the three most popular languages are:

  • C++
  • Python
  • Java

For instance, in the Google Code Jam 2017, among the top 3,000 coders:

  • 🥇 79% used C++
  • 🥈 16% used Python
  • 🥉 8% used Java

(Yes, that adds up to more than 100% because some folks use more than one language!)

Why Everyone Loves C++

C++ is like the Ferrari of programming languages in competitive programming — super fast and incredibly powerful.

It has:

  • A huge standard library (called STL — Standard Template Library)
  • Ready-to-use data structures like vector, map, and priority_queue
  • A perfect balance of speed and control

That’s why most top competitors prefer it. If you’re aiming for efficiency and raw speed — C++ is your go-to.

But Wait… Python Has Its Magic Too!

If you’ve ever used Python, you already know how elegant and simple it feels. You can often do in one line what might take five in C++ or Java.

Python shines in problems where:

  • You need to deal with big numbers (Python can handle huge integers natively)
  • You want to prototype quickly
  • Code readability and simplicity matter more than raw execution speed

For example, here’s how you can handle large integer arithmetic easily in Python:

# Python can handle large numbers effortlessly
a = 987654321987654321987654321
b = 123456789123456789123456789
print(a * b)

Try doing that in C++ — it’s a lot more work!

So, even though C++ might be faster, Python makes your life easier in many ways. That’s why some participants master both — using the right tool for the right problem.

Python Template

Now, in most C++ tutorials, you’ll see something like this:

#include <bits/stdc++.h>
using namespace std;

int main() {
    // solution comes here
}

That’s the classic C++ template — short, compact, and ready for battle. But let’s rewrite this idea in Python style, so you have your own starter template:

# --- Competitive Programming Template in Python ---

import sys
input = sys.stdin.readline  # Faster input for large test cases

def solve():
    # Write your solution here
    n = int(input())
    arr = list(map(int, input().split()))
    print(sum(arr))  # Example output

if __name__ == "__main__":
    solve()

A few quick notes:

  • sys.stdin.readline makes input faster (handy for large inputs).
  • Always wrap your code in a solve() function — it helps keep things organized.
  • Keep your code short and simple, so it’s easy to debug under time pressure.

Input and output

Let’s be honest — input and output (I/O) isn’t the most glamorous topic. But when you’re solving problems under time pressure, knowing how to handle I/O efficiently can make or break your success.

In competitive programming, speed matters — not just for algorithms, but for how you read and write data too.

So let’s break it down, step by step — the friendly, Pythonic way. 🐍

How Input and Output Work

In most programming contests, your program reads from standard input (the keyboard or an input file) and writes to standard output (the console or an output file).

In Python, this usually means using the built-in input() and print() functions — but there’s a catch: when the input is large, input() can be a bit slow.

That’s why most competitive programmers use sys.stdin.readline() for reading data — it’s much faster.

Reading Input

Let’s start simple. Imagine you’re given input like this:

123 456 monkey

You can read it easily in Python like this:

a, b, x = input().split()
a, b = int(a), int(b)
print(a, b, x)

When problems involve huge inputs, the standard input() might slow things down. In that case, use sys.stdin — a faster alternative.

Here’s a simple template:

import sys
input = sys.stdin.readline  # faster input

a, b = map(int, input().split())
x = input().strip()  # removes trailing newline
print(a, b, x)

A couple of tips here:

  • strip() removes the newline character \n at the end.
  • map(int, input().split()) quickly converts space-separated numbers into integers.

Writing Output

In contests, you usually use print() for output. For example:

a, b, x = 123, 456, "monkey"
print(a, b, x)

Want faster output for huge datasets? You can use sys.stdout.write() instead of print() — it skips some internal overhead.

Example:

import sys
sys.stdout.write(f"{a} {b} {x}\n")

Small optimization, but it can matter when your code runs thousands of times per second.

Reading Until There’s No More Data

Sometimes, you don’t know how many lines of input you’ll get — maybe until EOF (end of file). In that case, you can use a simple loop like this:

import sys

for line in sys.stdin:
    x = line.strip()
    # process x
    print(x)

This loop keeps reading until there’s no more data — perfect for problems where input size isn’t specified.

Using Files for Input and Output

Sometimes, contests or local testing require reading from files instead of standard input. Python makes this super easy.

Just redirect your streams like this:

import sys
sys.stdin = open("input.txt", "r")
sys.stdout = open("output.txt", "w")

# Now input() reads from input.txt
# and print() writes to output.txt

n = int(input())
print("Read from file:", n)

This is handy when testing locally, since you can save test cases and outputs in files.

Working with Numbers

Whether it’s integers, modular arithmetic, or floating-point precision, understanding how Python handles numbers can save you from subtle bugs and wrong answers.

Integers

Most programming problems revolve around integers — whole numbers like 1, -5, or 1000000.

In languages like C++, integers have strict size limits (like int for 32-bit or long long for 64-bit). But here’s the good news: Python automatically handles big integers! 🎉

That means in Python, you don’t need to worry about whether your number fits into 32 bits or 64 bits — it just works.

For example:

x = 123456789123456789123456789
print(x)

No overflow. No “long long” required. Python automatically adjusts the memory to store large integers.

Modular Arithmetic

Now, let’s talk about something that shows up in almost every contest — modular arithmetic.

“Modulo” (or mod) simply means the remainder after division. For example:

17 mod 5 = 2  →  because 17 = 3×5 + 2

When numbers get really large (like in combinatorics or Fibonacci problems), you only need the remainder instead of the full number. That’s why you’ll often see constraints like - “Output the answer modulo 1,000,000,007”

This is a special number (a prime) used in many contests.

You can safely take the remainder at any step of addition, subtraction, or multiplication:

(a + b) % m  =  (a % m + b % m) % m  
(a - b) % m  =  (a % m - b % m) % m  
(a * b) % m  =  (a % m * b % m) % m  

So instead of letting your numbers grow huge, just “mod” them after every operation.

Example

Let’s say we want to calculate n! % m (factorial of n modulo m).

Here’s how we do it in Python:

n = 10
m = 1_000_000_007

x = 1
for i in range(2, n + 1):
    x = (x * i) % m

print(x)

✅ The numbers never grow too large, and you stay safely within limits.

Sometimes, especially when subtracting, your remainder might turn out negative.

For example:

x = -3 % 5
print(x)  # Output: 2

Python handles this nicely — it always gives a positive remainder, unlike some other languages. Still, if you ever suspect negative remainders (like after subtraction), you can always do:

x = (x % m + m) % m

This guarantees your result stays between 0 and m-1.

Floating-Point Numbers

Now let’s move to decimals — numbers like 3.14159 or 0.00001. In Python, they’re called floats and behave similarly to C++’s double.

x = 3.1415926535
print(x)

That’s accurate enough for most problems — but there’s a catch.

⚠️ The Floating-Point Trap - Computers can’t represent every decimal exactly. For example:

x = 0.3 * 3 + 0.1
print(x)

You’d expect this to print 1.0, right? But it actually prints something like:

0.9999999999999999

That’s called a rounding error — and it’s totally normal in floating-point math.

Because of rounding errors, never use == to compare floats. Instead, check if they’re close enough by using a tiny threshold (epsilon ε):

a = 0.1 + 0.2
b = 0.3

if abs(a - b) < 1e-9:
    print("a and b are equal (within tolerance)")
else:
    print("a and b are not equal")

Here, 1e-9 means 0.000000001, which sets how precise you want the comparison to be.

Many problems ask you to print results with a specific number of decimal places. You can easily control this in Python:

x = 3.1415926535
print(f"{x:.9f}")   # Prints 9 decimal places

Output:

3.141592654

That’s clean, precise, and exactly what most contests expect.

Shortening Code

When you’re competing against the clock, every second counts ⏱️ — even when typing code. That’s why competitive programmers often write short, clean, and fast-to-type code. Think of it as learning “shorthand” for programming — your fingers (and your brain) will thank you later. 😄

In a contest, you don’t have hours to write perfect, verbose programs. You’re solving multiple problems in limited time — so shorter syntax helps you:

  • Type less
  • Reduce mistakes
  • Read and debug faster

That’s why coders often use short variable names, utility functions, and aliases. Let’s see how this works — the Python way. 🐍

Shorter Type Names

In C++, you might use typedef to create shorter names for data types. But in Python, things are simpler — you don’t need typedefs at all. Instead, you can just use shorter variable names or type hints if needed.

Example:

# No need for typedefs — just use variables directly
a = 123456789
b = 987654321
print(a * b)

If you want to be consistent with competitive programming style, you can define quick helpers for common structures like lists and pairs:

# Short aliases for commonly used types
vi = list        # vector<int> equivalent
pi = tuple       # pair<int, int> equivalent

Usage:

nums: vi = [1, 2, 3]
pair: pi = (5, 10)
print(nums, pair)

Simple, readable, and short!

Using Helper Functions

In C++, macros are often used to shorten repetitive code. But in Python, we don’t use macros. Instead, we can use helper functions or lambda expressions — they’re safer and clearer.

For example:

def mp(a, b):
    return (a, b)  # same as make_pair

def pb(v, val):
    v.append(val)  # same as push_back

Now you can do this:

v = []
pb(v, mp(1, 2))
pb(v, mp(3, 4))
print(v)  # [(1, 2), (3, 4)]

Cleaner, Pythonic, and no preprocessor headaches. 🧠

Mathematics

Mathematics is the heartbeat of competitive programming. It’s what turns clever ideas into efficient algorithms — and simple loops into elegant one-liners.

You don’t need to be a math genius, but you do need to understand the fundamentals. So, in this section, let’s explore the mathematical building blocks that show up again and again in problem-solving.

Sum Formulas

Ever noticed how certain number patterns keep repeating? Like the sum of the first n natural numbers or the sum of squares?

These are sum formulas, and they’re lifesavers when you need quick mathematical shortcuts.

Let’s look at some classic ones:

Example 1: Sum of First n Numbers

The formula is:

1+2+3++n=n(n+1)21 + 2 + 3 + \dots + n = \frac{n(n + 1)}{2}

In Python:

def sum_n(n):
    return n * (n + 1) // 2

print(sum_n(10))  # Output: 55

Example 2: Sum of Squares

The formula is:

12+22+32++n2=n(n+1)(2n+1)61^2 + 2^2 + 3^2 + \dots + n^2 = \frac{n(n + 1)(2n + 1)}{6}

In Python:

def sum_squares(n):
    return n * (n + 1) * (2 * n + 1) // 6

print(sum_squares(5))  # Output: 55

Arithmetic Progression (AP)

An arithmetic progression is a sequence where each term increases by a fixed difference.

Example: 3, 7, 11, 15 (difference = 4)

The formula for the sum of an AP is:

S=n(a+b)2S = \frac{n(a+b)}{2}

where

  • a = first term
  • b = last term
  • n = number of terms

In Python:

def ap_sum(a, b, n):
    return n * (a + b) // 2

print(ap_sum(3, 15, 4))  # Output: 36

Geometric Progression (GP)

In a geometric progression, each term is multiplied by a constant ratio.

Example: 3, 6, 12, 24 (ratio = 2)

The sum of the GP is:

S=bkak1S = \frac{bk-a}{k-1}

where

  • a = first term
  • b = last term
  • k = ratio between consecutive terms

In Python:

def gp_sum(a, b, k):
    return (b * k - a) // (k - 1)

print(gp_sum(3, 24, 2))  # Output: 45

And a special case to remember:

1+2+4+8+...+2n1=2n11+2+4+8+...+2^{n-1} = 2^n-1

Harmonic Sum

A harmonic sum looks like this:

1+12+13+...+1n1+\frac{1}{2}+\frac{1}{3}+...+\frac{1}{n}

It grows slowly — approximately like log₂(n) + 1. So if you ever need to estimate it, remember: it’s small even for large n.

In Python:

import math

def harmonic_sum(n):
    return sum(1 / i for i in range(1, n + 1))

print(harmonic_sum(6))  # Output: ~2.45

Set Theory

A set is a collection of unique elements. For example:

X = {2, 4, 7}
print(len(X))  # 3

Common Operations

OperationMeaningPython Equivalent
Intersection (A ∩ B)Common elementsA & B
Union (A ∪ B)Elements in either setA | B
Difference (A \ B)Elements in A but not BA - B
Complement (A¯)Elements not in A (depends on universal set)Use set subtraction
A = {1, 2, 5}
B = {2, 4}

print(A & B)  # {2}
print(A | B)  # {1, 2, 4, 5}
print(A - B)  # {1, 5}

A set with n elements always has 2^n subsets. Example:

from itertools import chain, combinations

def all_subsets(S):
    return list(chain.from_iterable(combinations(S, r) for r in range(len(S)+1)))

print(all_subsets({2, 4, 7}))

Logic

Logic forms the foundation of algorithms and conditions. Each logical statement is either True (1) or False (0).

Here are some common operators:

SymbolMeaningPython Equivalent
¬NOTnot
ANDand
ORor
Implicationif A: then B
EquivalenceA == B

Example :

A = True
B = False

print(not A)        # False
print(A and B)      # False
print(A or B)       # True
print((not A) or B) # False

You can also define predicates — conditions that return True or False.

Example:

def is_prime(x):
    if x < 2: return False
    for i in range(2, int(x ** 0.5) + 1):
        if x % i == 0:
            return False
    return True

print(is_prime(7))  # True
print(is_prime(8))  # False

Functions

Python gives you many built-in mathematical tools, like floor and ceiling functions:

import math

print(math.floor(3/2))  # 1
print(math.ceil(3/2))   # 2

You can also find the minimum and maximum of numbers easily:

print(min(1, 2, 3))  # 1
print(max(1, 2, 3))  # 3

Factorial and Fibonacci

Factorial (n!) means multiplying all numbers up to n.

def factorial(n):
    return 1 if n == 0 else n * factorial(n - 1)

print(factorial(5))  # Output: 120

Fibonacci numbers follow the rule:

f(n)=f(n1)+f(n2)f(n) = f(n-1)+f(n-2)

Here’s the Python version:

def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)

print([fib(i) for i in range(10)])

Or more efficiently (using iteration):

def fib_fast(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

Logarithms

A logarithm tells you how many times you divide by a base before reaching 1. For example:

log₂(32) = 5 because 32 → 16 → 8 → 4 → 2 → 1

In Python:

import math
print(math.log2(32))  # 5.0

Useful Log Rules

RuleFormula
Productlogₖ(ab) = logₖ(a) + logₖ(b)
Quotientlogₖ(a/b) = logₖ(a) - logₖ(b)
Powerlogₖ(xⁿ) = n * logₖ(x)
Change of baselogₐ(x) = logₖ(x) / logₖ(a)

In Python:

a, b, k = 2, 8, 2
print(math.log(a*b, k))  # log₂(16) = 4
print(math.log(a/b, k))  # log₂(0.25) = -2

Extra Tip

You can find the number of digits in an integer using logs too:

digits in x=log10(x)+1\text{digits in x} = ⌊log_{10}(x)⌋ +1
def num_digits(x):
    import math
    return math.floor(math.log10(x)) + 1

print(num_digits(123))  # Output: 3

Contests and Resources

If you’ve ever watched a programming competition and thought, “Wow, how do they even solve these problems so fast?” — this section is for you. Competitive programming is like a sport — it has its leagues, championships, training arenas, and study materials.

Let’s take a tour through the most famous contests and best resources to help you become a world-class problem solver. 🌍💻

IOI - The International Olympiad in Informatics

Think of IOI (International Olympiad in Informatics) as the Olympics of programming for high school students. It’s an annual global competition where each country sends a team of four brilliant minds to compete.

  • 🧠 Who can participate: Secondary school students
  • ⏱️ Format: Two five-hour contests
  • 📈 Problems: Three algorithmic problems per day, divided into subtasks with partial scoring
  • 🌍 Scale: ~300 participants from 80+ countries

Even though countries send teams, each student competes individually — no teamwork here, just pure brainpower.

Before making it to IOI, students go through national and regional contests such as:

  • Baltic Olympiad in Informatics (BOI)
  • Central European Olympiad in Informatics (CEOI)
  • Asia-Pacific Informatics Olympiad (APIO)

And if you want to train online, you can check out:

  • 🇭🇷 Croatian Open Competition in Informatics (COCI)
  • 🇺🇸 USA Computing Olympiad (USACO)
  • 🇵🇱 Polish Olympiad problem archives — packed with classic challenges

💡 Pro Tip: The IOI syllabus includes almost everything from this course — so if you master these topics, you’ll be IOI-ready!

ICPC — The Collegiate Showdown

If IOI is for school students, the ICPC (International Collegiate Programming Contest) is for university students — and it’s legendary.

Each team has three students and one computer, which means teamwork, strategy, and time management are key. (Yes, three people — one keyboard. It gets intense 😅)

  • ⏱️ Format: Five-hour contest
  • 🧩 Problems: Around 10 algorithmic problems
  • 💥 Scoring: Only perfect solutions that pass all test cases count

The Contest Journey

1. Local regionals → 2. National contests → 3. World Finals 🌎

Thousands of teams compete, but only around 100–150 make it to the finals. Reaching that stage is already a major accomplishment — it’s like qualifying for the World Cup of coding. ⚽💻

During the contest, teams can see the live scoreboard — but in the last hour, the board freezes. You can submit, but you won’t see the results until the end — making the finale super suspenseful!

While IOI focuses more on logic and algorithms, ICPC adds a stronger mathematical edge. Expect more problems involving combinatorics, number theory, and optimization.

Online Contests — Your Practice Arena

You don’t need to wait for an official competition — there are tons of online platforms hosting contests every week! These are perfect for practice, learning, and climbing the global leaderboard.

  • Codeforces - Weekly contests, two divisions:
    • Div2 → for beginners
    • Div1 → for advanced coders
  • AtCoder — Known for high-quality problems from Japan 🇯🇵
  • HackerRank — Great for interview-style problems
  • CS Academy — Clean UI and educational problem sets
  • Codechef - Weekly contests

Books - Your Trusted Companions

While practice is key, books help you understand the “why” behind each algorithm. Here are some of the best reads for competitive programmers:

📘 Beginner-Friendly

  • Steven Skiena & Miguel RevillaProgramming Challenges: The Programming Contest Training Manual - A great place to start — hands-on problems and clear explanations.
  • Steven Halim & Felix HalimCompetitive Programming 3 - A must-have for serious learners. Covers data structures, problem patterns, and contest strategy.

📗 Advanced Reads

  • Krzysztof Diks et al.Looking for a Challenge? - A legendary book from the University of Warsaw — not for beginners, but full of world-class problems.

📙 Algorithm Foundations

Even outside competitive programming, it’s crucial to build strong theoretical knowledge. Here are the top classics every programmer should know:

  • Thomas H. Cormen et al.Introduction to Algorithms (CLRS) - The ultimate algorithm bible. Deep but rewarding.
  • Jon Kleinberg & Éva TardosAlgorithm Design - Focuses on the why behind algorithms and optimization.
  • Steven SkienaThe Algorithm Design Manual - Explains algorithms with intuition, real-world insights, and practical applications.

Wrapping Up

Whether you’re a high schooler dreaming of IOI gold, a college student eyeing ICPC glory, or a coder looking to test your skills online — there’s a contest (and a learning path) for you.

Start small, practice regularly, and learn from every problem you solve (or get wrong — that’s part of the fun!).

Every great programmer you admire today started as a beginner typing out print("Hello World"). With the right mindset, consistency, and a bit of competitive fire — the next IOI or ICPC champion could be you. 🏅🔥