Algorithmshashmap last seen index

Last Seen Index with a Hash Map

TT
Testlaa Team
May 14, 20261 min read

Last seen index maps value→latest position—powers “minimum window substring”, recency eviction, or gap queries while scanning.

Why this shows up in the real world

Browser last visited URL per tab id; robotics last sensor event timestamp per device.

Core idea (explained for students)

Update last[x]=i each visit; compute distances with i - last[x] if problem asks for spacing between equal values.

Try this in Python

def last_seen(nums: list[int]) -> dict[int, int]:
    last: dict[int, int] = {}
    for i, x in enumerate(nums):
        last[x] = i
    return last


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

Common mistakes

  • Initializing last map for first occurrence logic vs last—read statement carefully.
  • 1-indexed vs 0-indexed statements.

Key takeaways

  • Pair with sliding minimum when window validity depends on recency.
  • For multi-character, key can be tuple.

Tags:

Hashing & frequencyPythonStudents