Walk a sequence and count occurrences of each value in a map. Classic "get current count, add one, write back" loop.

Algorithm

Canonical input ["fig", "apple", "fig", "pear", "apple", "fig"] produces the final map {fig: 3, apple: 2, pear: 1}.

Basic Implementation

basic.c
#include <stdio.h>
#include <string.h>

#define MAX_KEYS 16

int main(void) {
    const char *words[] = {"fig", "apple", "fig", "pear", "apple", "fig"};
    size_t n = sizeof(words) / sizeof(words[0]);
    const char *keys[MAX_KEYS];
    int counts[MAX_KEYS];
    int key_count = 0;
    for (size_t i = 0; i < n; ++i) {
        const char *word = words[i];
        int found = -1;
        for (int k = 0; k < key_count; ++k) {
            if (strcmp(keys[k], word) == 0) {
                found = k;
                break;
            }
        }
        if (found < 0) {
            keys[key_count] = word;
            counts[key_count] = 1;
            key_count++;
        } else {
            counts[found] = counts[found] + 1;
        }
    }
    printf("{");
    for (int k = 0; k < key_count; ++k) {
        if (k > 0) printf(", ");
        printf("%s: %d", keys[k], counts[k]);
    }
    printf("}\n");
    return 0;
}

Complexity

  • Time: O(n * k) for k distinct keys in this educational version; a real hash table would be O(n) average.
  • Space: O(k) where k is the number of distinct keys.

Implementation notes

  • C: parallel const char *keys[MAX_KEYS] and int counts[MAX_KEYS] arrays plus an explicit key_count keep the get-or-default branch visible — the lesson is teaching the bookkeeping, not the hash.
  • strcmp(keys[k], word) == 0 is the explicit string-equality test C uses where Python / Java / JavaScript / C++ have built-in map indexing.
  • The replay renders the map as a list of key/value rows in first-seen order and animates the count increment on each frame.
get-or-default A linear scan of `keys[]` finds the slot for the current word. A miss appends a new key with count `1` (the "default" branch); a hit reads the current count and writes count + 1.
first-seen order Keys are stored in first-seen order so the final printout is deterministic without leaning on a hash bucket order. C has no built-in hash map in its standard library, so parallel `keys[]` / `counts[]` arrays are the smallest honest container shape for this lesson.