PrepStack · Markdown HTML

Prefix state plus frequency hash

Prefix, difference, and hashed state · HTML

Formal shape

If interval (j,i] is valid exactly when relation(P[i],P[j]) holds, query the required historical key while scanning P[i], then insert the current prefix.

Recognition signals

False friends

SignalWhy it is different
One range-sum queryPlain prefix sum is simpler; no historical hash is needed.
No compact state encodingIf prefix summaries grow in dimension with n, hash-state storage may be impractical.

Core invariant

Before processing position i, the table contains exactly the historical prefixes allowed as left boundaries; query-before-insert avoids using a future or self state accidentally.

State, transition, and processing order

ItemDefinition
StateCurrent prefix P, state-to-frequency for counting or state-to-earliest-index for length, and the accumulated answer.
TransitionUpdate P, derive and query the matching historical key, contribute to the answer, then record current P.
Frontier / orderAll prefixes to the left of the scan, compressed by state in a hash table rather than expanded as intervals.

Python skeleton

def count_target_sum(values, target):
    prefix = 0
    frequency = {0: 1}
    answer = 0
    for value in values:
        prefix += value
        answer += frequency.get(prefix - target, 0)
        frequency[prefix] = frequency.get(prefix, 0) + 1
    return answer

Correctness sketch

  1. The sum of j..i is P[i+1]-P[j], equal to target exactly when historical P[j]=P[i+1]-target.
  2. frequency stores the number of eligible occurrences of each historical prefix, so the lookup counts exactly the valid intervals ending here.
  3. Every interval is counted in the unique iteration for its right endpoint, preventing omissions and duplicates.

Complexity

TimeSpaceParameters
Expected O(n)O(n)n is item count; hashing is expected O(1), with at most n+1 distinct prefix states.

Edge cases

Error patterns

PatternWhy it fails / fix
Forgetting the empty prefixEvery valid interval starting at index zero is lost.
Inserting before queryingSome targets then count a zero-length interval; define and respect boundary semantics.
Using the wrong table payloadCounts need frequency; longest length needs earliest index.

Selection and exclusion rules

RelationTemplateBoundary
monotone-case alternativeVariable-size sliding windowNonnegative values permit a forward-only left boundary.

Original micro-example

PartDetail
ResultThere are 3 valid intervals.
SetupValues [2,-2,2], target sum 2.
TracePrefixes are 2,0,2; each 2 matches a prior zero, and the final 2 has more than one possible left boundary.

Recall prompts

My notes