KatInterview

Find Minimum Index Gap Between Word Pairs

Data Structure DesignAuto-graded · 22 test cases
EasyAuto-gradedData Structure Designhash-maptwo-pointerspreprocessing

Last 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 sequence
  • operations: a list of operation names
  • arguments: 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) <= 30000
  • 1 <= len(words[i]) <= 10
  • Each word consists of uppercase and lowercase English letters only
  • At most 5000 operations will be provided
  • For "shortest" operations, both queried words exist in words and 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.