Design Data Structures · Pattern 10 of 10

Simulation designs: model the state directly

When the limits are small, the simplest correct design is to store the state exactly as described and scan it. A memory of n cells is an array of owner ids, and each call walks it once.

1 variation · 1 problem

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Small limits (around 1000) on both size and number of calls
  • The rules describe the state step by step
  • First fit, leftmost free block, or "free everything with this id"

The template

Simulation
class Allocator {
    int[] mem;                                   // mem[i] = id that owns cell i, 0 if free
    Allocator(int n) { mem = new int[n]; }
    int allocate(int size, int mID) {
        int run = 0;                             // free cells in a row, ending at i
        for (int i = 0; i < mem.length; i++) {
            run = mem[i] == 0 ? run + 1 : 0;
            if (run == size) {                   // leftmost block that fits
                for (int j = i - size + 1; j <= i; j++) mem[j] = mID;
                return i - size + 1;
            }
        }
        return -1;
    }
    int freeMemory(int mID) {
        int count = 0;
        for (int i = 0; i < mem.length; i++)
            if (mem[i] == mID) { mem[i] = 0; count++; }
        return count;
    }
}

The variations

  1. 1Store the state as described, then scan

    One array cell per memory unit, holding its owner. Allocation finds the first run of size free cells in one pass; freeing clears every cell with that id. With bigger limits, a sorted map of free blocks makes each call O(log n).

Mistakes to avoid

  • Not resetting the free-run counter when you hit a used cell, so two separate gaps are glued together.
  • Assuming one id owns one block: the same id can allocate several times, and freeMemory must free all of them.
  • Reaching for an interval tree when n and the calls are only 1000: O(n) per call is plenty.
Back to Design Data Structures →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.