Closest Pair Gaps Between Words in a Fixed List
Data Structure DesignAuto-graded · 16 test casesLast updated
Answer many closest-index-distance queries over a fixed word list by building a position index, precomputing same-word gaps, and binary searching the smaller list.
Closest Pair Gaps Between Words in a Fixed List
You are given a fixed list of words, and a batch of queries is run against it. Each query names two words and asks how close together they appear in the list.
For a query (a, b), the answer is the smallest value of |i - j| over all index pairs where words[i] == a, words[j] == b, and i != j.
The two query words may be identical. In that case you need the smallest distance between two different positions holding that same word.
Function
Implement closest_word_gaps(words, ops, args_list):
words: the list of strings to search.ops: a list of operation names.args_list: a list the same length asops. Entrykholds the arguments forops[k].
Walk through ops and args_list in order. For each entry where ops[k] == "shortest", args_list[k] is a two-element list [a, b], and you must compute the answer for that query. Ignore every entry whose operation name is anything other than "shortest" (for example a constructor-style entry such as "WordDistance"); such entries produce no output.
Return a list of integers containing one answer per "shortest" entry, in the same order as the queries appear.
Notes
- The distance is symmetric, so the order of
aandbdoes not affect the answer. - Since the word list never changes between queries, work that depends only on
wordsshould be done once rather than repeated for every query.
Constraints
2 <= len(words) <= 100,0001 <= len(words[i]) <= 10, and each word consists only of lowercase English letters.- Both query words are guaranteed to occur in
words. - If a query uses the same word twice, that word is guaranteed to occur at least twice in
words. - There are at most
50,000"shortest"queries. - Scanning the whole list for every query will be too slow.
Examples
Example 1
Input: closest_word_gaps(['practice', 'makes', 'perfect', 'coding', 'makes'], ['shortest', 'shortest', 'shortest'], [['coding', 'practice'], ['makes', 'coding'], ['makes', 'makes']])
Output: [3, 1, 3]
Example 2
Input: closest_word_gaps(['a', 'c', 'b', 'a', 'a'], ['shortest', 'shortest'], [['a', 'b'], ['a', 'a']])
Output: [1, 1]
Hints
Hint 1
Because the list never changes, build something once up front: for each word, the sorted list of indices where it occurs.
Hint 2
For a query on the same word twice, the best pair is always two neighbouring entries in that word's index list, so the minimum neighbouring gap can be precomputed per word.
Hint 3
For two different words, loop over the shorter index list and, for each index, binary search the longer list. Only the first element at or after it and the element just before it can be the closest.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Scanning the list once per query would cost up to 100,000 x 50,000 steps, which is too slow. Since words never changes, we do the shared work once.
- Position index. Make one left-to-right pass and record, for every word, the list of indices where it appears. Each list is automatically sorted.
- Same-word queries. For a word with at least two occurrences, store the minimum difference between consecutive entries of its index list. A query with
a == bis then a dictionary lookup. - Different-word queries. Take the shorter of the two index lists and call it
small; the other islarge. For each positionpinsmall, usebisect_leftonlargeto find the first index>= p, and also look at the entry just before it. Keep the smallest difference seen. - Process
opsandargs_listtogether, skip any operation that is not"shortest", and append one answer per query.
Why it is correct
- Same word. For any two positions
x < yof one word in a sorted list, every entry between them lies in between, so some adjacent pair has a gap no larger thany - x. The minimum therefore occurs at an adjacent pair. The guarantee of at least two occurrences means the stored value exists. - Different words. For a fixed
p, the closest element oflargeis either the smallest element>= por the largest element< p. Those are exactly the entries atbisect_leftand just before it. Anything further out on either side is at least as far fromp. Taking the minimum over allpinsmallcovers every candidate optimal pair. - The
i != jrule. Different words never share an index, so the condition is automatically satisfied. The same-word case handles it by only comparing distinct entries. - Initial
best.len(words)exceeds any real distance (at mostN - 1), and both words exist, so it is always replaced. - Iterating over the shorter list is valid because the distance is symmetric.
Complexity
Let N = len(words), and for a query let m and M be the lengths of the shorter and longer index lists.
- Preprocessing: O(N) time and O(N) space.
- Same-word query: O(1).
- Different-word query: O(m log M).
Reference solution
from bisect import bisect_left
from collections import defaultdict
from typing import List
def closest_word_gaps(words: List[str], ops: List[str], args_list: List[List[str]]) -> List[int]:
# word -> sorted list of positions
positions = defaultdict(list)
for idx, w in enumerate(words):
positions[w].append(idx)
# smallest gap between two occurrences of the same word
same_gap = {}
for w, idxs in positions.items():
if len(idxs) >= 2:
same_gap[w] = min(idxs[i] - idxs[i - 1] for i in range(1, len(idxs)))
answers = []
for op, args in zip(ops, args_list):
if op != "shortest":
continue
a, b = args
if a == b:
answers.append(same_gap[a])
continue
small = positions[a]
large = positions[b]
if len(small) > len(large):
small, large = large, small
best = len(words)
for p in small:
at = bisect_left(large, p)
if at < len(large):
best = min(best, large[at] - p)
if at > 0:
best = min(best, p - large[at - 1])
answers.append(best)
return answers