Answer Repeated Shortest Word Distance Queries
Company: LinkedIn
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
# Answer Repeated Shortest Word Distance Queries
You are given a fixed array `words` and many queries. Each query contains two distinct words that both appear in the array.
For each query, return the minimum absolute difference between an index containing the first word and an index containing the second word.
Implement:
```text
shortestWordDistances(words, queries) -> integer[]
```
Preprocess the word array once, then answer queries in order. Word comparison is case-sensitive, and repeated identical queries must produce repeated answers.
## Constraints
- `1 <= words.length <= 200,000`
- `1 <= queries.length <= 200,000`
- Every query has exactly two distinct words present in `words`.
## Examples
### Example 1
```text
words = ["practice", "makes", "perfect", "coding", "makes"]
queries = [["coding", "practice"], ["makes", "coding"]]
output = [3, 1]
```
### Example 2
```text
words = ["a", "b", "a", "c", "b", "a"]
queries = [["a", "b"], ["a", "c"], ["a", "b"]]
output = [1, 1, 1]
```
Quick Answer: Preprocess a fixed word array and answer many shortest-distance queries between distinct repeated words. The prompt defines case-sensitive matching, ordered batch outputs, repeated queries, valid-word guarantees, and input sizes that reward indexed occurrence lists and two-pointer scans.
You are given a fixed array words and many queries. Each query contains two distinct words that both appear in the array. For each query, return the minimum absolute difference between an index containing the first word and an index containing the second word. Preprocess the word array once, answer queries in their original order, compare words case-sensitively, and produce a separate answer for every repeated query.
Constraints
- 1 <= words.length <= 200,000
- 1 <= queries.length <= 200,000
- Every query has exactly two distinct words present in words.
- Word comparison is case-sensitive.
Examples
Input: (['a', 'b'], [['a', 'b']])
Expected Output: [1]
Explanation: The only two positions are adjacent.
Input: (['practice', 'makes', 'perfect', 'coding', 'makes'], [['coding', 'practice'], ['makes', 'coding']])
Expected Output: [3, 1]
Explanation: The first source example returns one answer per query in order.
Hints
- Store the sorted positions at which each word occurs.
- Repeated queries may reuse a previously computed distance but still need repeated output entries.