Basics

These concepts and techniques are the building blocks of most solutions, whatever the problem is about and whatever language it is written in.

Time complexity

Two programs may solve the same problem quickly for 100 numbers. With a million numbers, one may finish in a fraction of a second, while the other takes hours. Can we predict this difference without running them?

Arrays and vectors

Suppose we need to read the scores of 100 students and print them in reverse order. To do this, we need to store all the scores before printing them. Instead of declaring a separate variable for each score, we can use an array.

Strings

A program may need to check whether a word reads the same forwards and backwards, count the letters in a text or find every occurrence of a pattern. In each case, we need to work with a sequence of characters rather than just a single number.

Pairs and tuples

An olympiad ranking contains both the participant's ID and their score. If we store them in separate arrays and sort only the scores, the scores no longer belong to the correct participants.

Floating-point numbers

When calculating the average of two integers, the result is not necessarily an integer. For example, the average of 3 and 4 is 3.5. To represent such values, we use floating-point numbers.

Big integers

The factorial of 25 contains 26 digits, but a long long can hold only about 19. To calculate every digit of such an answer, we can store the number as a sequence of digits and perform arithmetic ourselves.

Sorting

Given a list of numbers, finding the pair with the smallest absolute difference by comparing every possible pair takes O(n^2) time. After arranging the numbers in order, we only need to compare neighbouring elements.

Counting sort

Suppose we need to sort one million exam results, each an integer from 0 to 100. Using a comparison-based algorithm such as std::sort takes O(n\log n) time for integers. However, there are only 101 possible scores. We can count how many times each score occurs instead of comparing individual elements.

Coordinate compression

Suppose we want to count how many times each value occurs in an array containing 700, 1000000000, 25, 700, 4000 and 25. A counting array indexed directly by these values would require more than a billion elements, even though the array contains only four distinct values. Instead, we can assign a small index to each distinct value and use those indices in the counting array.

Prefix sums

Suppose an array contains a million integers and we need to answer a million questions about the sum of elements in different ranges. Summing each range separately may require 10^{12} operations, even though many ranges overlap.

2D prefix sums

A map of a forest is represented as a rectangular grid, where each cell contains either a tree or an empty plot. We need to answer many queries asking how many trees are inside a given rectangle. Checking every cell of every rectangle can be too slow.

Binary search

Searching for a value in an array of one million elements may take one million comparisons. If the array is sorted, we can discard roughly half of the remaining elements after each comparison.

Ternary search

Suppose we want to make an open box from a square sheet of cardboard by cutting equal squares from its four corners and folding up the sides. The size of the cuts determines the volume of the box. Increasing the cut size initially increases the volume, but eventually makes the base too small.

Two pointers

Suppose we need to find the longest consecutive range of non-negative numbers whose sum does not exceed a given limit. Trying every possible starting and ending position takes O(n^2) time even if we can calculate each range sum in constant time. Neighbouring ranges share many of their elements, so instead of examining each range separately, we can maintain its boundaries and update them as we process the array.

Sweep line

A monitoring system records when each machine starts and stops working. We want to determine the total time during which at least one machine was running. Simply adding the working times of all machines is not enough, because several machines may work simultaneously. Checking every moment separately can also be impractical when the time range is large.

Recursion

A folder can contain files and other folders. To calculate its total size, we need to calculate the size of each folder inside it, which may contain more folders of its own.

Bitmasks

Suppose a shop has several products, and we need to find every selection whose total price is exactly a given amount. Each product can either be selected or left out. With products, there are 2^n possible selections.

Greedy algorithms

A cashier needs to give change using as few coins as possible. Choosing the largest coin that fits seems natural, but whether this produces an optimal answer depends on the available denominations.

Backtracking

Suppose we need to generate every possible arrangement of five distinct cards. We can choose a card for the first position, then choose one of the remaining cards for the second position, and continue until the arrangement is complete. After recording one arrangement, we return to an earlier choice and try another possibility.

Grids

In the game Minesweeper, each empty cell displays the number of mines in its neighbouring cells. To calculate these numbers, we need a convenient way to represent the board, visit neighbouring cells and determine whether they are inside the board.

Number systems

The same number can be written in different ways: 44 in decimal, 101100 in binary, 54 in octal, or 2C in hexadecimal. Although their representations differ, they all describe the same value.

Brute force

A shop sells pens for 3 coins and notebooks for 5 coins. We have exactly 15 coins and want to determine how many different combinations of these products we can buy. Since there are only a few possible quantities of each product, we can examine every combination and check whether its total price is exactly 15.

Was this page helpful?