easy +10 pts

Word to Index Map

Build a mapping from each word to its first occurrence index in a given list of words.

Write a function `word_to_index_map(words)` that takes a list of strings and returns a dictionary where each unique word is a key and the value is the index of its first occurrence in the list (0-based). The order of the keys in the dictionary does not matter. If the list is empty, return an empty dictionary.

Constraints

The input list will contain at most 10^5 strings. Each string is non-empty and consists of lowercase and uppercase letters, digits, and underscores. The function should run in O(n) time where n is the length of the list.

Example

[">>> word_to_index_map(['apple', 'banana', 'apple', 'cherry'])", "{'apple': 0, 'banana': 1, 'cherry': 3}", '>>> word_to_index_map([])', '{}']
10 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Iterate over the list with `enumerate` to get both index and word.
Check if a word is already a key in the dictionary before assigning.
Remember that dictionaries preserve insertion order in Python, but the order doesn't matter for equality.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.