Preparation for district competitions: 7th and 8th grade

Welcome to the page dedicated to preparing for the district computer science competitions for 7th and 8th grade. This page is part of a complete preparation programme that assumes basic knowledge of the subject, and here that knowledge is extended with the specific topics of the competition syllabus. On this page you can find the key topics, example tasks, explanations and interactive tools that will help you prepare better for competitions.

Introduction


This page is a guide to preparing for the tasks that appear at the district computer science competitions, the regional level for pupils of the 7th and 8th grade. The material here supplements the basic curriculum, and you can find more detailed basics and extra examples through the links provided.

Extra preparation and practice can also be done on the site: https://takprog.petlja.org/osnovnaskola/posts/27.

This guide contains simple examples that are parts of larger tasks and serve as a basis for further work and improvement in solving combinatorial, geometric and algorithmic problems.


Analysing subseries

In this section we look at how an input series can be split into smaller subseries. Examples include:

  • Subseries of fixed length – for example, grouping daily values into weeks (subseries of 7 consecutive elements).
  • Subseries with a separator – for example, a sequence of numbers divided by zeros, where zero is used as the separator between subseries.

Here are two examples with explanations and code:

Example 1: Subseries of fixed length (weeks)

Suppose we have a sequence of daily values and we want to divide it into subseries of 7 consecutive elements, which corresponds to the weeks of a year. In this example the program reads the number of daily values, then reads the values and finally prints the weekly groups.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cout << "Enter the number of daily values: ";
    cin >> n; // Read the number of elements
    vector<int> daily(n);
    cout << "Enter the daily values: " << endl;
    for (int i = 0; i < n; i++) {
        cin >> daily[i]; // Read one value
    }
    cout << "Subseries (weeks):" << endl;
    for (int i = 0; i < n; i++) {
        cout << daily[i] << " ";
        if ((i + 1) % 7 == 0)
            cout << endl; // Move to a new line after every 7 elements
    }
    return 0;
}

Example 2: Subseries with a separator

In this example the input sequence of numbers contains subseries separated by zero as the separator. For example, if the input is: 5 3 7 0 8 9 2 0 4 1, then the sequence is divided into three subseries:

  • 5 3 7 – the elements before the first zero,
  • 8 9 2 – the elements between the first and the second zero,
  • 4 1 – the elements after the second zero.

The program recognises zero as the separator and extracts all the subseries for further processing.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> numbers;
    int x;
    cout << "Enter the numbers (0 as the separator): " << endl;
    while (cin >> x) {
        numbers.push_back(x); // Store the numbers entered in a vector
    }
    cout << "Subseries:" << endl;
    vector<int> segment;
    for (int i = 0; i < numbers.size(); i++) {
        if (numbers[i] == 0) {
            for (int j = 0; j < segment.size(); j++) {
                cout << segment[j] << " ";
            }
            cout << endl;
            segment.clear(); // Clear the segment after printing it
        } else {
            segment.push_back(numbers[i]); // Add the number to the current segment
        }
    }
    if (!segment.empty()) {
        for (int j = 0; j < segment.size(); j++) {
            cout << segment[j] << " ";
        }
        cout << endl;
    }
    return 0;
}

These examples show how an input series can be split into smaller segments (subseries) depending on the given criterion (fixed length or separator). This technique is useful in data analysis and in preparing for computer science competitions.

For more information and examples, see the resources on the page: Strings in C++.

For more information about vectors in C++, see the resources on the page: Vectors in C++.

Test your code here

#include <iostream>
using namespace std;

int main() {
    // Write your C++ code here...
    cout << "Hello!" << endl;
    return 0;
}

Transformations of arrays


Building a new array from an existing one


In this example we will build a new array that contains only the even numbers from an existing array. This demonstrates how we can take certain elements from the original array and put them into a new array. The resulting array can have fewer elements than the original one.

The program takes the existing array, checks the condition for each element, and then adds the elements that meet the condition (even numbers) to the new array.

#include <iostream>
using namespace std;

int main() {
    const int size = 8;                            // Size of the original array
    int original[size] = {1, 2, 3, 4, 5, 6, 7, 8}; // Original array
    int evens[size];                               // Array for the even numbers (at most size elements)
    int count = 0;                                 // Counter of the new elements
    for (int i = 0; i < size; i++) {
        if (original[i] % 2 == 0) {
            evens[count] = original[i]; // Add the even number to the new array
            count++;                    // Increase the counter
        }
    }
    cout << "New array (even numbers only): " << endl;
    for (int i = 0; i < count; i++) {
        cout << evens[i] << " ";
    }
    cout << endl;
    return 0;
}

Moving elements within an array (cyclic shift)


In this example we show how the elements of an array can be shifted cyclically to the right by a given number of places. The program uses a temporary array to store the last k elements, then moves the remaining elements to the right, and finally puts the temporary elements back at the beginning.

This is useful when you need to rotate the elements of an array, for example in competition problems.

#include <iostream>
using namespace std;

int main() {
    const int size = 8;
    int arr[size] = {1, 2, 3, 4, 5, 6, 7, 8};
    int k; // Number of places for the cyclic shift
    cout << "Enter the number of places for the cyclic shift: ";
    cin >> k;
    // Normalise k (if k is larger than the size of the array)
    k = k % size;
    if (k == 0) {
        cout << "The array stays the same." << endl;
        return 0;
    }
    int temp[k]; // Temporary array for the last k elements

    // Store the last k elements in the temporary array
    for (int i = 0; i < k; i++) {
        temp[i] = arr[size - k + i];
    }
    // Move the remaining elements to the right
    for (int i = size - 1; i >= k; i--) {
        arr[i] = arr[i - k];
    }
    // Put the elements from the temporary array back at the beginning
    for (int i = 0; i < k; i++) {
        arr[i] = temp[i];
    }
    cout << "The array after the cyclic shift: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    return 0;
}

These examples show how a new array can be built from an existing one using loops, and how the elements of an array can be moved cyclically. These techniques are very important in solving data-manipulation problems at computer science competitions.

For more information, see the resources on the page: Arrays in C++.

Introduction to matrices


Matrices (two-dimensional arrays) are a key structure for organising and processing data in programming. They let us arrange data in rows and columns, which is very important for solving many different problems – from simple tables to complex mathematical and statistical analyses.

For more information about the basics of working with matrices in C++, visit the page Two-dimensional arrays in C++. If you are interested in the dynamic approach and working with matrices, see also the page Two-dimensional dynamic arrays and matrices in C++.

Example 3: Computing statistics over a matrix

In this example we have a matrix and need to calculate the basic statistics: the sum, product, minimum and maximum of all the elements. We also do a linear search for a given element, mapping (transforming every element) and filtering (extracting the elements that meet a condition).

#include <iostream>
using namespace std;

int main() {
    const int rows = 3, cols = 4;
    int matrix[rows][cols] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
    int sum = 0, prod = 1, minVal = matrix[0][0], maxVal = matrix[0][0];
    bool found = false;
    int searchValue = 7;
    int mapped[rows][cols];    // New array with the transformed elements
    int filtered[rows * cols]; // Array for the filtered elements
    int countFiltered = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            int val = matrix[i][j];
            sum += val;
            prod *= val;
            if (val < minVal)
                minVal = val;
            if (val > maxVal)
                maxVal = val;
            if (val == searchValue)
                found = true;
            mapped[i][j] = val * 2; // Mapping: every element is doubled
            if (val % 2 == 0) {
                filtered[countFiltered] = val;
                countFiltered++;
            }
        }
    }
    cout << "Sum: " << sum << endl;
    cout << "Product: " << prod << endl;
    cout << "Min: " << minVal << endl;
    cout << "Max: " << maxVal << endl;
    cout << "Element " << searchValue << " " << (found ? "was found." : "was not found.") << endl;
    cout << "Mapped matrix:" << endl;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << mapped[i][j] << " ";
        }
        cout << endl;
    }
    cout << "Filtered even numbers:" << endl;
    for (int i = 0; i < countFiltered; i++) {
        cout << filtered[i] << " ";
    }
    cout << endl;
    return 0;
}

Example 4: Statistics over rows, columns and diagonals

In this example we have a square matrix and calculate statistics for each row, column and the main diagonals. For example, we can calculate the maximum in each row and then choose the smallest of those maximums – a combination called "the minimum of the maximums".

#include <iostream>
using namespace std;
int main() {
    const int size = 3;
    int matrix[size][size] = {{5, 7, 3}, {9, 2, 8}, {4, 6, 1}};
    // Calculate the maximum in each row
    int rowMax[size];
    for (int i = 0; i < size; i++) {
        int maxVal = matrix[i][0];
        for (int j = 0; j < size; j++) {
            if (matrix[i][j] > maxVal)
                maxVal = matrix[i][j];
        }
        rowMax[i] = maxVal;
    }
    // Find the smallest of the row maximums
    int minOfRowMax = rowMax[0];
    for (int i = 1; i < size; i++) {
        if (rowMax[i] < minOfRowMax)
            minOfRowMax = rowMax[i];
    }
    cout << "The minimum of the row maximums: " << minOfRowMax << endl;
    return 0;
}

Example 5: Accessing rectangular and triangular parts of a matrix

This example shows how to access the elements of a rectangular part of a matrix, as well as a triangular part. For example, we can extract a rectangular sub-array or the lower triangular part of a matrix.

#include <iostream>
using namespace std;
int main() {
    const int rows = 4, cols = 4;
    int matrix[rows][cols] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
    // Rectangular sub-array: the elements from rows 1-2 and columns 2-3
    cout << "Rectangular sub-array:" << endl;
    for (int i = 1; i <= 2; i++) {
        for (int j = 2; j <= 3; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    // Triangular sub-array: the lower triangular part of the matrix
    cout << "Lower triangular part of the matrix:" << endl;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < rows; j++) {
            if (j <= i)
                cout << matrix[i][j] << " ";
            else
                cout << "0 ";
        }
        cout << endl;
    }
    return 0;
}

These examples show how a matrix can be analysed in several ways: by calculating statistics, searching, mapping, filtering, and accessing particular segments of the matrix.

For more information, see the resources on the page: Arrays in C++.

Accessing the elements of rectangular and triangular parts of a matrix


In this section we show how, using nested loops, we can access a particular part of a matrix. For example, from a square matrix we can extract a rectangular sub-array or a triangular part.

Example 1: Accessing the elements of a rectangular part of a matrix

In the following example we have a 4x4 matrix. The program extracts the elements from rows 1 and 2 and columns 2 and 3, which forms a rectangular sub-array.

#include <iostream>
using namespace std;

int main() {
    const int rows = 4, cols = 4;
    int matrix[rows][cols] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
    // Extract the rectangular part: rows 1 and 2 (indexes 1 and 2) and columns 2 and 3 (indexes 2 and 3)
    cout << "Rectangular sub-array:" << endl;
    for (int i = 1; i <= 2; i++) {
        for (int j = 2; j <= 3; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

Example 2: Moving a rectangular part within a matrix

In this example we show how to move a given rectangular part of a matrix to a new position inside the same matrix. Suppose we want to move the sub-array defined by rows 1 and 2 and columns 1 and 2 to the position that starts at row 2 and column 2.

#include <iostream>
using namespace std;
int main() {
    const int rows = 4, cols = 4;
    int matrix[rows][cols] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
    // The rectangular part to move: rows 1 and 2, columns 1 and 2
    int temp[2][2];
    // Copy the sub-array into a temporary array
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            temp[i][j] = matrix[i + 1][j + 1];
        }
    }
    // Move the copied part to the new position: starting at row 2, column 2
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            matrix[i + 2][j + 2] = temp[i][j];
        }
    }
    // Print the matrix after moving
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << matrix[i][j] << "\t";
        }
        cout << endl;
    }
    return 0;
}

These examples demonstrate two techniques: building a new array (by filtering or transforming elements) and moving rectangular parts inside a matrix. These techniques are key for analysing and processing data in matrix tasks, and they are especially useful at computer science competitions.

For more information, visit: Arrays in C++.

Methods of algorithm efficiency 1


Efficient sorting of an array

In many tasks, especially at competitions, efficient sorting of an array is key to optimising algorithms. Instead of quadratic time (O(n²)) for simple sorting methods, the library function sort (from <algorithm>) sorts in an average time of O(n log n). This gives a faster way to count the distinct elements or to find the intersection of two arrays.

For more detailed explanations of efficient array sorting and binary search, visit the pages: Sorting arrays. Binary search.

In the following example the array is sorted, and then the function unique and arithmetic operations are used to count the distinct elements:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
    vector<int> arr = {5, 3, 8, 5, 2, 8, 1};
    // Sort the array in ascending order
    sort(arr.begin(), arr.end());
    cout << "Sorted array: " << endl;
    for (int x : arr) {
        cout << x << " ";
    }
    // Count the distinct elements
    int distinct = unique(arr.begin(), arr.end()) - arr.begin();
    cout << "\nNumber of distinct elements: " << distinct << endl;
    return 0;
}

Binary search of a sorted array

When the array is sorted, the function binary_search (from <algorithm>) can quickly find whether a given element is in the array. This method has a time complexity of O(log n), compared with linear search, which takes O(n). Also, using lower_bound and upper_bound we can find the number of occurrences of a given element.

The following example shows how to do a binary search and count the occurrences of the element 5 in a sorted array:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
    vector<int> arr = {1, 2, 3, 4, 5, 5, 5, 6, 7};
    // The array is already sorted; if it were not, call: sort(arr.begin(), arr.end());

    bool found = binary_search(arr.begin(), arr.end(), 5);
    cout << "Element 5 " << (found ? "was found." : "was not found.") << endl;
    // Count the occurrences of element 5
    int count = upper_bound(arr.begin(), arr.end(), 5) - lower_bound(arr.begin(), arr.end(), 5);
    cout << "Number of occurrences of element 5: " << count << endl;
    return 0;
}

Elements of number theory 1


This topic covers the basic concepts of number theory, including calculating the number and the sum of the divisors of a natural number, checking whether a number is prime, and finding prime numbers. Understanding these basics is key to solving many tasks, especially at competitions.

1. The number and the sum of the divisors of a natural number

For a given natural number we need to find all its divisors and work out how many there are and what their sum is. For example, for the number 12 the divisors are 1, 2, 3, 4, 6 and 12, and their sum is 28.

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter a natural number: ";
    cin >> n;
    int count = 0, sum = 0;
    for (int i = 1; i <= n; i++) {
        if (n % i == 0) {
            count++;  // Increase the number of divisors
            sum += i; // Add the divisor
        }
    }
    cout << "Number of divisors: " << count << endl;
    cout << "Sum of the divisors: " << sum << endl;
    return 0;
}

2. Checking whether a number is prime

A number is prime if it has exactly two divisors, 1 and the number itself. The following example checks whether the number entered is prime using a simple loop.

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter a number: ";
    cin >> n;
    bool isPrime = true;
    if (n < 2) {
        isPrime = false;
    } else {
        for (int i = 2; i * i <= n; i++) {
            if (n % i == 0) {
                isPrime = false;
                break; // A divisor was found, so the number is not prime
            }
        }
    }
    cout << n << (isPrime ? " is prime." : " is not prime.") << endl;
    return 0;
}

For more resources and examples about prime numbers and factorisation, see the page: Prime numbers and factorisation.

Factorising a number into primes and its applications

In this topic we look at how a number can be factorised into its prime factors using simple algorithms with a complexity of O(√n). From the factorisation we can calculate the smallest natural number by which the given number must be multiplied to get a perfect square or a perfect cube. This approach is very important in competition tasks where optimised solutions are required.

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter a number: ";
    cin >> n;

    // Factorise the number into primes
    cout << "Prime factors of the number: ";
    int original = n;
    for (int i = 2; i * i <= n; i++) {
        while (n % i == 0) {
            cout << i << " ";
            n /= i;
        }
    }
    if (n > 1)
        cout << n;
    cout << endl;
    // Application: the smallest natural number we must multiply the given number by to get a perfect square
    int multiplier = 1;
    n = original;
    for (int i = 2; i * i <= n; i++) {
        int count = 0;
        while (n % i == 0) {
            count++; // Count the exponent
            n /= i;
        }
        if (count % 2 == 1)
            multiplier *= i; // If the exponent is odd, i goes into the multiplier
    }
    if (n > 1)
        multiplier *= n;
    cout << "Smallest multiplier for a perfect square: " << multiplier << endl;
    return 0;
}

GCD and LCM using Euclid's algorithm

Euclid's algorithm lets us quickly calculate the greatest common divisor (GCD) of two numbers. From the GCD we can easily calculate the least common multiple (LCM). These techniques are often used in problems such as simplifying fractions or optimising competition tasks.

#include <iostream>
using namespace std;

int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}
int main() {
    int a, b;
    cout << "Enter two numbers: ";
    cin >> a >> b;
    int g = gcd(a, b);
    int lcm = (a / g) * b; // The LCM is calculated using the GCD

    cout << "GCD: " << g << endl;
    cout << "LCM: " << lcm << endl;
    cout << "Simplified fraction: " << (a / g) << "/" << (b / g) << endl;
    return 0;
}

You can study these examples in more detail on the pages: Prime numbers and factorisation. Euclid's algorithm.

Elements of algorithm efficiency 2


A competitor should be able to estimate the time complexity of the algorithm they use. This means it is important to understand the basic principles of analysing algorithms, so that you can predict how fast a program will perform certain operations. For a basic introduction to algorithm efficiency, see the information on the portal petlja.org.

Many problems can be solved more efficiently than with the naive solution by applying one or more techniques. Examples of these techniques include:

  • Optimising loops (reducing the number of iterations, or replacing nested loops with a single loop when possible),
  • Using dynamic programming to eliminate repeated calculations,
  • The "divide and conquer" technique for solving complex problems faster,
  • Using more efficient data structures, such as hash tables or priority queues,
  • Using sorting and binary search instead of linear search,
  • Applying memoisation in recursive algorithms.

Understanding these techniques lets competitors recognise when a naive solution can be improved and choose the most efficient approach to the given problem.

Elements of algorithm efficiency 2 – Transforming arrays

In this topic we look at two techniques that improve the efficiency of algorithms:

  1. Using mathematical formulas: Instead of going through all the elements of an array (which takes linear time), we can calculate the sum or other operations with known formulas in constant time. For example, the sum of the first n terms of an arithmetic sequence is calculated with the formula: S = n/2 * (2a + (n - 1)*d), where a is the first term, d is the common difference and n is the number of terms.
  2. Incremental calculation: Instead of calculating a value from the start every time (which can take quadratic time), the previous result is used to calculate the next one quickly. Examples of this are calculating all the prefix sums, or the factorials of the numbers from 1 to n.

Here are concrete examples with explanations and comments in the code:

Example 1: The sum of the first n terms of an arithmetic sequence

The program reads the first term a, the common difference d and the number of terms n and then calculates the sum using the formula: S = n/2 * (2a + (n - 1)*d). This calculation is done in constant time.

#include <iostream>
using namespace std;
int main() {
    double a, d; // a: first term, d: common difference
    int n;       // Number of terms
    cout << "Enter a, d and n: ";
    cin >> a >> d >> n;
    double S = n / 2.0 * (2 * a + (n - 1) * d); // Calculate the sum with the formula
    cout << "Sum of the first n terms: " << S << endl;
    return 0;
}

Example 2: Calculating prefix sums

In this example an array of whole numbers is read, and then for each element of the array the prefix sum is calculated – the sum of all the elements from the start of the array up to the current element. This approach is efficient because each sum is calculated incrementally from the previous result, which takes linear time.

#include <iostream>
#include <vector>
using namespace std;
int main() {
    int n;
    cout << "Enter the number of elements of the array: ";
    cin >> n;
    vector<int> arr(n);
    cout << "Enter the elements of the array: " << endl;
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    vector<int> prefixSums(n);
    prefixSums[0] = arr[0]; // The first prefix sum is the first element
    for (int i = 1; i < n; i++) {
        prefixSums[i] = prefixSums[i - 1] + arr[i]; // Incremental calculation of the prefix sums
    }
    cout << "Prefix sums: " << endl;
    for (int i = 0; i < n; i++) {
        cout << prefixSums[i] << " ";
    }
    cout << endl;
    return 0;
}

For more information about techniques for transforming and generating arrays, and about an efficient approach to analysing algorithms, see the resources on the page: Arrays in C++.

The two pointer technique


The two pointer technique is an optimised method for solving problems that involve iterating through arrays or lists. It is used when we need to efficiently find certain pairs of elements, split data into segments, or process an array in a single pass.


How it works


Two pointers (indexes) are placed at different positions in the array, usually at:

  • The beginning and the end (for problems with sums and searching for pairs).
  • Two consecutive elements (for problems with merging and moving data).
  • Different parts of the array (for specific tasks such as sorting or partitioning).

Example: Finding two numbers in a sorted array that give a certain sum


We have a sorted array and want to find two numbers whose sum is a certain value target. Instead of using two nested for loops (O(n2)), we use two pointers for a solution in O(n) time complexity.
At the start the pointers point to the beginning and the end of the array. We check whether the sum of the elements they point to is equal to the required value (target). If it is, the loop stops; if it is not, we look at two cases:
1) the sum is smaller than required and needs to be increased – in that case the left pointer moves to the right, because the array is sorted in ascending order, so this increases the sum.
2) the sum is larger than required, so it needs to be decreased. This is done by moving the right pointer to the left, towards smaller values.


#include <iostream>
using namespace std;

bool twoSum(int arr[], int n, int target) {
    int left = 0, right = n - 1;

    while (left < right) {
        int sum = arr[left] + arr[right];

        if (sum == target) {
            cout << "The numbers are: " << arr[left] << " and " << arr[right] << endl;
            return true;
        } else if (sum < target) {
            left++; // Move the left pointer (we need a larger sum)
        } else {
            right--; // Move the right pointer (we need a smaller sum)
        }
    }
    return false;
}

int main() {
    int arr[] = {1, 2, 4, 7, 11, 15};
    int target = 9;
    int n = sizeof(arr) / sizeof(arr[0]);

    if (!twoSum(arr, n, target)) {
        cout << "There are no such numbers!" << endl;
    }
    return 0;
}

Explanation of the code:


- We set two pointers: left at the beginning of the array and right at the end of the array.
- We calculate the sum of the elements: arr[left] + arr[right].
- If the sum is smaller than the target, we increase left (we need a larger number).
- If the sum is larger, we decrease right (we need a smaller number).
- If the sum is equal to the target, we print the numbers and finish the search.
- The loop repeats until the pointers meet.


Where is this technique used?


  • Searching in a sorted array (as in the example above).
  • Finding the greatest length of a subarray with certain properties.
  • Rearranging an array without extra memory (e.g. moving all the zeros to the end).
  • Finding triangle triplets in a sorted array.

Advanced data structures in problem solving


Advanced data structures, such as tuples, dictionaries, maps and sets make it possible to solve programming problems more efficiently. They help organise data in a way that allows faster searching, sorting and access, which optimises algorithms and reduces the total running time.

For example, using dictionaries or maps lets us quickly find pairs of elements with certain properties (such as finding all the pairs whose sum is a given value), because the search takes O(log n) or even O(1) time in the case of hash maps. On the other hand, sets are used to test membership quickly and to remove duplicates, while tuples let us store data of different types in a fixed order.

By combining these structures with efficient algorithms, such as sorting and binary search, you can get much better performance when solving complex problems. This is especially important in competition tasks, where the efficiency of the algorithm is key.

For more information and examples of using these advanced data structures, visit the page: Dictionaries, maps and sets in C++.

Using tuples/structures, dictionaries/maps and sets in C++ for efficient algorithms


Advanced data structures such as tuples, dictionaries, maps and sets make it possible to solve problems quickly and efficiently. Below is an example of finding the pairs of array elements that give a given sum S. This example uses unordered_map to record the numbers from the array, which allows searching in an average time of O(1).

#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;

void findPairsHashMap(vector<int>& arr, int S) {
    unordered_map<int, int> seen;            // A map that records the numbers seen so far
    for (int number : arr) {                 // Go through all the numbers in the array
        int needed = S - number;             // Calculate the complementary number
        if (seen.find(needed) != seen.end()) { // If the complementary number was found
            cout << "Pair: (" << needed << ", " << number << ")\n";
        }
        seen[number]++; // Record the current number in the map
    }
}
int main() {
    vector<int> arr = {1, 4, 7, 3, 2, 5, 8};
    int S = 9;                  // The given sum
    findPairsHashMap(arr, S);   // Call the function that finds the pairs
    return 0;                   // End of the program
}

Explanation of the solution

In this solution, for each element x of the array the complementary number is calculated (S - x). If the complementary number has already been recorded in the map, it means there is a pair whose sum is S and that pair is printed. Using unordered_map makes searching fast, so this algorithm is efficient, with a time complexity of O(n).

For more information about maps and dictionaries, see the resources on the page: Dictionaries and maps in C++.

Using prefix and suffix sums and combining the previous techniques


In this topic we will show how to use techniques that reduce the time complexity of algorithms:

  • Using mathematical formulas: Instead of calculating step by step, some operations (e.g. the sum of an arithmetic sequence) can be calculated in constant time using known formulas.
  • Incremental calculation: Calculating prefix or suffix sums lets us quickly get the sum of any segment of an array; this is linear in the size of the array and much faster than a quadratic solution.
  • Combining the previous techniques: By combining sorting, maps/sets and incremental calculation we can solve more complex tasks, such as the number of occurrences of a given element in an unsorted array or finding the triples whose sum is a given value.

Here are examples with explanations and comments in the code:

Example 1: Calculating prefix sums

This example demonstrates how prefix sums, i.e. the sum of all the elements from the beginning up to each index, can be calculated in a single pass through the array. This lets us later answer a query about the sum of any segment of the array quickly, reducing the time complexity from O(n²) to O(n).

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cout << "Enter the number of elements of the array: ";
    cin >> n;
    vector<int> arr(n);
    cout << "Enter the elements of the array: " << endl;
    for (int i = 0; i < n; i++) {
        cin >> arr[i]; // Read the elements of the array
    }
    vector<int> prefix(n);
    prefix[0] = arr[0]; // The first element is the starting sum
    for (int i = 1; i < n; i++) {
        prefix[i] = prefix[i - 1] + arr[i]; // Incremental calculation of the prefix sums
    }
    cout << "Prefix sums: " << endl;
    for (int i = 0; i < n; i++) {
        cout << prefix[i] << " ";
    }
    cout << endl;
    return 0;
}

Example 2: Triples of array elements with a given sum

In this example all the triples of elements whose sum is a given value are found in an unsorted array. The naive solution uses three nested loops with a time complexity of O(n³); this is the starting point, which can be improved by combining the previous methods (sorting and two pointers).

#include <iostream>
#include <vector>
using namespace std;
int main() {
    int n, target;
    cout << "Enter the number of elements of the array: ";
    cin >> n;
    vector<int> arr(n);
    cout << "Enter the elements of the array: " << endl;
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    cout << "Enter the target value: ";
    cin >> target;
    // Find all the triples whose sum is equal to target
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            for (int k = j + 1; k < n; k++) {
                if (arr[i] + arr[j] + arr[k] == target) {
                    cout << "Triple: (" << arr[i] << ", " << arr[j] << ", " << arr[k] << ")" << endl;
                }
            }
        }
    }
    return 0;
}

These examples show how different techniques can be combined to optimise problem solving. For more information about transforming and generating arrays and about efficient algorithms, visit the resource: Arrays in C++.

Overflow and the memory complexity of an algorithm


In this example we show two important aspects:

  • Overflow: When large numbers in an array are added using the type int, an overflow can happen if the sum is greater than the largest value that type can hold. This can lead to wrong results.
  • Memory complexity: The algorithm for adding up an array needs memory proportional to the number of elements in the array, i.e. O(n). Choosing the right data type helps optimise memory use.

The following example demonstrates adding up the elements of an array using the type int and points out the possibility of an overflow, as well as the linear memory complexity of the algorithm.

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter the number of elements of the array: "; // Read the number of elements
    cin >> n;
    // Allocate the array – memory complexity O(n)
    int arr[1000]; // We assume that n is not greater than 1000

    for (int i = 0; i < n; i++) {
        cin >> arr[i]; // Read the elements of the array
    }
    int sum = 0; // Add up the elements of the array
    for (int i = 0; i < n; i++) {
        sum += arr[i]; // Possible overflow if the sum is too large
    }
    cout << "Sum of the elements of the array: " << sum << endl;
    // This algorithm has time complexity O(n) and memory complexity O(n)

    return 0;
}

Introduction to recursion


New lesson: recursion is explained in detail in the lesson Introduction to recursion and in the guide Recursion and backtracking.

Recursion is a technique in which a function calls itself to solve a smaller part of the problem and then combines the results to get the solution of the whole problem. This method is especially useful when a problem can be divided into similar subproblems. For a more detailed explanation of recursive algorithms, visit the page: Recursive algorithms.

Example: Calculating the factorial (n!) recursively

In the following example the recursive function factorial calculates the factorial of the number n. If n is less than or equal to 1, the function returns 1 (the base case). Otherwise, the function returns the product of the number n and the factorial of n-1 (the recursive case).

#include <iostream>
using namespace std;
int factorial(int n) {
    if (n <= 1) { // Base case: 0! and 1! are equal to 1
        return 1;
    } else { // Recursive case: n! = n * (n-1)!
        return n * factorial(n - 1);
    }
}
int main() {
    int n;
    cout << "Enter a number: ";
    cin >> n;
    cout << "The factorial of " << n << " is " << factorial(n) << endl;
    return 0;
}

Using recursion in combinatorial problems


Recursion is a technique in which a function calls itself to solve a smaller part of the problem and then combines the results to get the solution of the whole problem. This method is especially useful in combinatorial tasks, where all possible n-tuples, permutations, combinations and variations are generated. Although recursive solutions often have exponential time complexity, they are elegant and easy to implement when the input data are small.

Below are examples for two subtopics:

  • Generating n-tuples with recursion (e.g. binary n-tuples with no two consecutive ones),
  • Generating the permutations of an array with recursion.

For more information about recursion and combinatorics, visit the resources on the relevant pages.

Example 1: Generating binary n-tuples with no two consecutive ones

This example uses recursion to generate all binary n-tuples (strings of length n made of '0' and '1') with the condition that there are no two consecutive '1's. The function calls itself and adds '0' or '1' to the current string, and the condition makes sure that if the last character is '1', the next one must be '0'.

#include <iostream>
#include <string>
using namespace std;

void generateBinaryTuples(string curr, int n) {
    if (curr.size() == n) {
        cout << curr << endl; // The n-tuple is complete, so we print it
        return;
    }
    if (curr.empty() || curr.back() == '0') {
        generateBinaryTuples(curr + '0', n); // We can add '0'
        generateBinaryTuples(curr + '1', n); // We can also add '1'
    } else {
        generateBinaryTuples(curr + '0', n); // If the last character is '1', the next one must be '0'
    }
}
int main() {
    int n;
    cout << "Enter the length of the n-tuple: ";
    cin >> n;
    generateBinaryTuples("", n);
    return 0;
}

Example 2: Generating the permutations of an array

In this example we recursively generate all the permutations of an array of whole numbers. The function permute uses the backtracking technique to swap the elements of the array and print every arrangement.

#include <iostream>
#include <vector>
using namespace std;

void permute(vector<int>& arr, int start) {
    if (start == arr.size() - 1) {
        for (int x : arr)
            cout << x << " ";
        cout << endl;
        return;
    }
    for (int i = start; i < arr.size(); i++) {
        swap(arr[start], arr[i]); // Swap the elements
        permute(arr, start + 1);
        swap(arr[start], arr[i]); // Put the elements back (backtracking)
    }
}
int main() {
    vector<int> arr = {1, 2, 3};
    permute(arr, 0);
    return 0;
}

For more information about recursion and generating combinatorial objects, see the resources on the relevant pages.