PrepStack · Markdown HTML

Frequency table / coordinate counting

Prefix, difference, and hashed state · HTML

Formal shape

Build count[x]=|{i:a[i]=x}|. Compute later results only from keys and counts; consuming an instance decrements its count and may delete the key at zero.

Recognition signals

False friends

SignalWhy it is different
Adjacency order mattersA frequency map discards positions and arrangement, so it cannot recover sequence patterns.
Huge sparse numeric domainDo not allocate through the maximum value; use hashing or coordinate compression.

Core invariant

After scanning a prefix, count[x] equals x's exact multiplicity there; counts stay nonnegative and their sum equals inserted items minus consumed items.

State, transition, and processing order

ItemDefinition
StateAn array or dictionary key→count, plus optional distinct count, maximum frequency, or frequency buckets.
TransitionOn input x increment count[x]; on matching or consumption verify positivity, decrement, and optionally remove a zero key.
Frontier / orderScanned items are compressed into counts, and the key domain replaces input indexes as the next iteration domain.

Python skeleton

def multiset_equal(left, right):
    if len(left) != len(right):
        return False
    count = {}
    for value in left:
        count[value] = count.get(value, 0) + 1
    for value in right:
        remaining = count.get(value, 0)
        if remaining == 0:
            return False
        if remaining == 1:
            del count[value]
        else:
            count[value] = remaining - 1
    return not count

Correctness sketch

  1. After the first pass, count is an exact multiset representation of left.
  2. Each right item must consume one equal instance; a missing instance immediately proves inequality.
  3. With equal lengths, complete consumption leaves an empty map exactly when every key has equal multiplicity.

Complexity

TimeSpaceParameters
Expected O(n+m)O(k)n and m are lengths and k is distinct keys; a small finite-domain array provides deterministic O(1) access.

Edge cases

Error patterns

PatternWhy it fails / fix
Using a set and losing multiplicity{a,a,b} and {a,b,b} have the same set but different multisets.
Leaving zero keys while using map lengthIf distinct count is dictionary size, delete zero-frequency keys.
Allocating an uncontrolled value-domain arrayA huge max-min span wastes memory; use hashing.

Selection and exclusion rules

RelationTemplateBoundary
hash foundationData-structure design / operation invariantThe API mainly maintains keys and counts
canonical-key countingGCD / LCM and divisibilityGrouping normalized ratios
optimization-context0/1 or unbounded knapsack DPMany identical item weights can be grouped before bounded-use processing.
same hash, different objectPrefix state plus frequency hashThe counted keys are historical prefix states rather than raw values.
factor aggregationSieve and prime factorizationCounting occurrences of each prime
state summaryExplicit simulation / state machineOnly a bounded distribution of counts drives the future
window-state componentVariable-size sliding windowCounts describe only the active contiguous window.
frequency rankingTop-K bounded heapSelect the k highest-frequency keys from count.
alternativeTwo heaps for streaming medianThe domain is small and insertions, deletions, and rank queries coexist.
unordered finite-domain alternativeOpposite-direction two pointersCounts can match complementary values directly.
deduplication aidSame-direction / read-write pointersRetention depends on global occurrence counts.

Original micro-example

PartDetail
ResultThe multisets are equal despite different order.
SetupCompare [r,r,s] with [s,r,r].
TraceThe left table is {r:2,s:1}; consuming the right side empties it.

Recall prompts

My notes