File: find-anagram-mappings/solution.py

Date: 2026-06-06

Time: 16:35

Purpose

This file solves LeetCode 760 — Find Anagram Mappings. Given two arrays nums1 and nums2 where nums2 is an anagram (permutation) of nums1, it returns an index mapping mapping such that mapping[i] = j means nums1[i] == nums2[j].

It's one solution module in a large repository of LeetCode implementations, each following the same structure: solution.py + test_solution.py + optional plan.md/review.md.

Key Components

anagramMappings(nums1, nums2) -> list[int] — The sole public function. Takes two integer lists of equal length where one is a permutation of the other, and returns a list of indices mapping each element in nums1 to a matching position in nums2.

Patterns

The solution uses inverted-index lookup with consumption: it pre-indexes all positions in nums2 by value, then pops from each value's queue as positions are consumed. This is the standard O(n) pattern for this problem.

The choice of deque over a plain list is deliberate — deque.pop() is O(1) from the right, same as list.pop(), but using deque signals intent: this is a queue of available indices being consumed. In practice list.pop() would perform identically here since it pops from the right, but deque makes the "pool of positions" semantics explicit.

The defaultdict(deque) pattern avoids any key-existence checks — every value in nums1 is guaranteed to appear in nums2 (anagram precondition), so the deque is never empty when popped.

Dependencies

Imports: defaultdict and deque from collections — both stdlib, no external dependencies.

Imported by: The testsolution.py files listed in the context aren't actually importing *this* file — that list appears to be a repo-wide cross-reference artifact. The real consumer is find-anagram-mappings/testsolution.py.

Flow

1. Build index_map: iterate nums2 with enumerate, appending each (value -> index) pair into the deque for that value.

2. Consume the map: for each value in nums1, pop an index from index_map[val]. The result list is built in a single list comprehension.

For nums1 = [12, 28, 46], nums2 = [46, 12, 28]:

Invariants

Error Handling

None. The function trusts the caller to satisfy the anagram precondition. An invalid input (missing value) would surface as an IndexError from deque.pop() on an empty deque — unhandled, which is appropriate for a LeetCode solution where inputs are guaranteed valid.

Topics to Explore

Beliefs