Chapter 9

Home

Counting and Summation Patterns

Two patterns appear in almost every beginner problem: counting how many things have a property, and summing values. These are the building blocks of harder algorithms.

Pattern: Running Total

Keep a variable that accumulates a result as you process each element.

Problem: Is it prefix-equal?

Given N and an array, how many prefixes have a sum equal to some target?

C++

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

int main() {
    int n, target; cin >> n >> target;
    int count = 0, running = 0;
    for (int i = 0; i < n; i++) {
        int x; cin >> x;
        running += x;
        if (running == target) count++;
    }
    cout << count << "\n";
    return 0;
}

Rust

use std::io::{self, Read};

fn main() {
    let mut input = String::new();
    io::stdin().lock().read_to_string(&mut input).unwrap();
    let nums: Vec<i64> = input
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let n = nums[0] as usize;
    let target = nums[1];
    let arr = &nums[2..2 + n];
    let mut count = 0;
    let mut running = 0;
    for x in arr {
        running += x;
        if running == target {
            count += 1;
        }
    }
    println!("{}", count);
}

Pattern: Frequency Counter

Count how many times each value appears. Use an array indexed by the value itself (when values are small, e.g. 0–100).

Problem: Most frequent number

Given N and N integers in range 0–100, find the most frequent value.

Sample input:
10
1 3 2 3 4 1 3 2 5 3

Expected output:
3

C++

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

int main() {
    int n; cin >> n;
    int freq[101] = {0};  // values 0..100
    for (int i = 0; i < n; i++) {
        int x; cin >> x;
        freq[x]++;
    }
    // find max frequency
    int best = 0;
    for (int i = 1; i <= 100; i++) {
        if (freq[i] > freq[best]) best = i;
    }
    cout << best << "\n";
    return 0;
}

Rust

use std::io::{self, Read};

fn main() {
    let mut input = String::new();
    io::stdin().lock().read_to_string(&mut input).unwrap();
    let nums: Vec<usize> = input
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let n = nums[0];
    let arr = &nums[1..=n];
    let mut freq = [0; 101];
    for &x in arr { freq[x] += 1; }
    let best = (0..=100).max_by_key(|&i| freq[i]).unwrap();
    println!("{}", best);
}

Pattern: Conditional Counting

Count items that satisfy a condition — even numbers, positive values, elements above a threshold.

C++

int count = 0;
for (int x : arr) {
    if (x > 0) count++;
}

Rust

let count = arr.iter().filter(|&&x| x > 0).count();

Key Takeaways

Practice