Algorithmshashmap first occurrence

First Occurrence with a Hash Map

TT
Testlaa Team
May 14, 20261 min read

First occurrence maps each value to the smallest index where it appeared—useful for “distance to duplicate”, uniqueness windows, or building from left scan.

Why this shows up in the real world

Parser records first declaration line; data quality flags first anomaly timestamp.

Core idea (explained for students)

Single pass: if x not in first: first[x]=i. For streaming reset policy depends on problem (sliding window may clear old keys).

Try this in Python

def first_index_each(nums: list[int]) -> dict[int, int]:
    first: dict[int, int] = {}
    for i, x in enumerate(nums):
        first.setdefault(x, i)
    return first


print(first_index_each([2, 1, 2, 3]))

Common mistakes

  • Overwriting first with latest accidentally when logic meant earliest.
  • Off-by-one when comparing distances with stored index.

Key takeaways

  • Combine with stack for “next greater” variants.
  • Store (index, value) tuples when tie-breaking.

Tags:

Hashing & frequencyPythonStudents