Find Minimum Index Gap Between Word Pairs
Data Structure DesignAuto-graded · 22 test casesLast updated
Tests the ability to preprocess data for efficient repeated lookups using hash maps and two-pointer merging of sorted lists.
You are given a list of words and need to handle multiple queries asking for the smallest index gap between two different words.
Write a function that processes a sequence of operations on a word list. The function receives:
words: a list of strings representing the word sequenceoperations: a list of operation namesarguments: a list of argument lists, one per operation
For each operation named "shortest", the arguments are two distinct words [word1, word2]. You must find the minimum absolute difference between any index where word1 appears and any index where word2 appears in the original words list.
For any operation name other than "shortest", produce no output for that operation.
Return a list containing the result of each "shortest" operation in order.
Both words in a "shortest" query are guaranteed to exist in words and are always different from each other. Words are case-sensitive.
Constraints
1 <= len(words) <= 300001 <= len(words[i]) <= 10- Each word consists of uppercase and lowercase English letters only
- At most
5000operations will be provided - For
"shortest"operations, both queried words exist inwordsand are distinct
Examples
Example 1
Input: word_distance_queries(['practice', 'makes', 'perfect', 'coding', 'makes'], ['shortest', 'shortest'], [['coding', 'practice'], ['makes', 'coding']])
Output: [3, 1]
Example 2
Input: word_distance_queries(['a', 'b', 'c', 'a', 'b'], ['shortest', 'shortest'], [['a', 'b'], ['a', 'c']])
Output: [1, 1]
Hints
Hint 1
Build an index mapping each word to all positions where it appears—this avoids rescanning the entire list for every query.
Hint 2
The position lists are naturally sorted since you encounter words left to right. Use a two-pointer technique to find the closest pair.
Hint 3
When comparing indices from two sorted lists, always advance the pointer pointing to the smaller value—this guarantees you won't miss the optimal pairing.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Since the function will process multiple queries against the same word list, we should avoid scanning the entire list for each query. The efficient strategy has two phases:
-
Preprocessing: Build a hash map where each word maps to all indices where it appears. Since we traverse
wordsfrom left to right, these index lists are automatically sorted in ascending order. -
Query processing: For each
"shortest"operation, retrieve the two sorted index lists and use a two-pointer technique to find the pair with minimum gap. Start both pointers at the beginning of their respective lists. At each step, compute the absolute difference between the current indices, then advance whichever pointer points to the smaller index. Continue until one list is exhausted.
Why It Works
The key insight is that advancing the pointer at the smaller index never causes us to miss the optimal pair.
Suppose we're comparing indices a[i] and b[j] where a[i] < b[j]. Any future index b[k] with k > j satisfies b[k] >= b[j] > a[i], which means the gap |a[i] - b[k]| is at least as large as |a[i] - b[j]|. Therefore, b[j] is the best remaining partner for a[i], and we've already measured that distance. We can safely move past a[i] by incrementing its pointer.
The same logic applies symmetrically when b[j] < a[i]. Since the words are distinct, their indices never overlap, so we never have equality.
By systematically pairing each index with its optimal remaining counterpart before discarding it, we're guaranteed to encounter the globally optimal pair during the scan.
We can also stop early: since the two words occupy different indices, the minimum possible gap is 1. Once we find a gap of 1, no improvement is possible.
Complexity
Let N = number of words, Q = number of queries, and assume each word appears O(N) times in the worst case.
Time:
- Preprocessing: O(N) to build the index map
- Per query: O(|positions_a| + |positions_b|), which is O(N) in the worst case when both words appear frequently
- Total: O(N + Q·N), approximately 1.5×10⁸ operations at the upper limits
In practice, most words appear rarely, and the early exit at gap=1 often triggers, making queries much faster than the worst case.
Space: O(N) to store the index map. Each position appears exactly once across all lists.
Implementation
from typing import List
from collections import defaultdict
def word_distance_queries(words: List[str], operations: List[str], arguments: List[List[str]]) -> List[int]:
# Build index: map each word to its sorted list of positions
word_positions = defaultdict(list)
for idx, word in enumerate(words):
word_positions[word].append(idx)
results = []
for operation, args in zip(operations, arguments):
if operation == "shortest":
word1, word2 = args
positions_a = word_positions[word1]
positions_b = word_positions[word2]
# Two-pointer merge to find minimum gap
ptr_a = ptr_b = 0
min_gap = len(words)
while ptr_a < len(positions_a) and ptr_b < len(positions_b):
min_gap = min(min_gap, abs(positions_a[ptr_a] - positions_b[ptr_b]))
# Move pointer at smaller index forward
if positions_a[ptr_a] < positions_b[ptr_b]:
ptr_a += 1
else:
ptr_b += 1
# Early termination: gap cannot be smaller than 1
if min_gap == 1:
break
results.append(min_gap)
return results