Problem · Array
Repeated Shortest Word Distance Queries
Learn this problemProblem statement
You are given an array words and a batch of queries. Each query contains two distinct words that both appear in words.
For each query [first, second], return the minimum absolute difference between an index containing first and an index containing second.
Preprocess words once, then answer every query. Return the distances in query order.
Function
shortestWordDistances(words: String[], queries: String[][]) → int[]Examples
Example 1
words = ["practice","makes","perfect","coding","makes"]queries = [["coding","practice"],["makes","coding"],["practice","makes"]]return = [3,1,1]coding and practice occur at indices 3 and 0. The closest makes to coding is at index 4, and the closest makes to practice is at index 1.
Example 2
words = ["a","b","a","c","b","a"]queries = [["a","b"],["a","c"],["b","c"]]return = [1,1,1]Each queried pair has adjacent occurrences somewhere in the array, so every minimum distance is 1.
Example 3
words = ["red","blue","green","yellow","red","green"]queries = [["blue","yellow"],["red","green"],["yellow","red"]]return = [2,1,1]The only blue and yellow positions differ by 2. The later red is adjacent to both green at index 5 and yellow at index 3.
Constraints
2 ≤ words.length ≤ 200000.1 ≤ queries.length ≤ 200000.- Every word contains
1to40lowercase English letters. - Each query contains exactly two distinct words, and both words occur in
words. - The total number of characters across
wordsandqueriesis at most2 * 10^6.