Lesson 6 of 12

Which axis are you prefixing?

Count values in a numeric interval or letters inside a substring.

Prefixes over possible values

A query asking how many observations have values in [L, R] is different from a query about positions [L, R]. Build freq[0..U], then C[0] = 0 and C[v + 1] = C[v] + freq[v]. C[t] counts observations with value strictly below t.

The inclusive value-range answer is C[R + 1] − C[L]. Allocate U + 2 prefix entries so value zero and the upper endpoint are both handled. For [3, 0, 3, 5, 1, 3], value interval [1, 3] contains four observations wherever they occurred.

Prefixes over positions, with one column per letter

A whole-word letter table forgets arrangement: aabb and bbaa have equal overall counts but different first-two-character counts. Preserve position information with P[i][c] = count of letter c in the first i characters.

Copy row i − 1 into row i, then increment the column for text[i − 1]. A query for letter c in inclusive positions [l, r] is P[r][c] − P[l − 1][c]. Starting every row from zero would store only one character instead of the cumulative prefix.

C++23
// Complete C++23 program. Input: lowercase ASCII word q, then l r letter.
#include <iostream>
#include <string>
#include <vector>
int main() {
    std::string text;
    int q;
    std::cin >> text >> q;
    int n = static_cast<int>(text.size());
    std::vector<std::vector<int>> pref(n + 1, std::vector<int>(26, 0));
    for (int i = 1; i <= n; ++i) {
        pref[i] = pref[i - 1];
        ++pref[i][text[i - 1] - 'a'];
    }
    while (q--) {
        int l, r;
        char c;
        std::cin >> l >> r >> c;
        int id = c - 'a';
        std::cout << pref[r][id] - pref[l - 1][id] << '\n';
    }
}

Columns cost memory and time

With alphabet size σ, copying every row costs O(σn), storage is O(σn), and a query about one letter costs O(1). For 26 letters and 100000 characters, raw four-byte counts alone occupy about 10.4 MB, before vector-row overhead.

Do not extend one prefix column per key to an enormous alphabet automatically. Storing sorted occurrence positions for each value and using two binary searches is another representation, connecting to Session 5’s map of vectors.

Frequency array

The value becomes an index. Each arrival increases freq[value] by one. This domain has ten possible values.

Input values

20
11
22
33
24
55

freq[value] — indices are values

00
11
32
13
04
15
06
07
08
09

The frequencies add up to 6, the number of input values.

Guided simulation · Change the inputs to test your understanding.

Pause & predict

For C[t] = number of observations with value < t, what does C[4] − C[1] count?

Choose an answer
Try it yourself

Turn the idea into code

In abacaba, count a in positions [2, 6], b in [1, 7], and a in [4, 4]. Explain the zero-based character conversion.

Give me a hint

Write positions 1 through 7 above the letters. A prefix row i consumes text[i − 1].

Show the explained solution

The answers are 2, 2, and 0. The a occurrences in [2,6] are positions 3 and 5; b occurs at 2 and 6; position 4 is c. Convert the one-based character position i to string index i − 1 only when reading the character.

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.