Lesson 4 of 12

Count values with direct indexing

Size the domain, handle signed keys with offsets, and find a mode.

The index now represents a value

An ordinary sequence stores a[position] = value. A frequency table stores freq[value] = occurrence count. For [3, 0, 3, 5, 1, 3], the counts over values 0 through 5 are [1, 1, 0, 3, 0, 1]. freq[3] describes how often 3 occurs, not the third input position.

For a guaranteed domain [0, U], allocate U + 1 zero entries. The domain controls size, even when only a few observations arrive. Initialization costs O(U + 1), input costs O(n), and q exact queries cost O(q), giving O(U + n + q + 1) time and O(U + 1) storage.

Offsets translate a bounded domain

For known values from LOW through HIGH, use index = value − LOW and allocate HIGH − LOW + 1 entries. For [−1000, 1000], −1000 maps to 0 and 1000 to 2000. Apply the same mapping during both insertion and lookup.

An offset does not shrink a huge domain. Shifting [−10⁹, 10⁹] still needs over two billion entries. Use a map or compression for sparse large values. abs(value), modulo, and clamping are not general index fixes: they merge different values. Validate out-of-domain application input before indexing.

Distinct counts and tie-breaking

Count positive frequency entries to get the number of distinct values. To report the smallest mode, scan values in ascending order and update only for a strictly greater frequency. A nonempty input guarantees some positive count replaces an initially absent candidate.

Frequency tables forget arrangement. They can print values in sorted order, but they cannot reconstruct the original order or identify the first unique input occurrence unless that order is preserved separately.

C++23
// Complete C++23 program. Input: n upper, n values in [0,upper]; n >= 1.
#include <iostream>
#include <vector>
int main() {
    int n, upper;
    std::cin >> n >> upper;
    std::vector<int> freq(upper + 1, 0);
    for (int i = 0; i < n; ++i) {
        int x;
        std::cin >> x;
        ++freq[x];
    }
    int distinct = 0, best = 0;
    for (int x = 0; x <= upper; ++x) {
        if (freq[x] > 0) ++distinct;
        if (freq[x] > freq[best]) best = x;
    }
    std::cout << distinct << '\n';
    std::cout << best << ' ' << freq[best] << '\n';
}

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

Five inputs may range from 0 through 100. How large must a direct frequency vector be?

Choose an answer
Try it yourself

Turn the idea into code

For domain [−3, 3], give the allocated size and indices for −3, 0, 3. Explain why using abs(x) would be wrong.

Give me a hint

Use x − LOW with LOW = −3.

Show the explained solution

Allocate 7 entries. The values map to indices 0, 3, and 6. Taking absolute values would merge −3 and 3, even though the task counts them as different values.

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.