204. Shortest Word Distance Between Words

Asked in

Shortest Word Distance Between Words
Design a class that is initialized with a list of words.

After initialization, the class must support repeated queries asking for the shortest distance between two different words in the original list.

The distance between two words is the absolute difference between their indices in the list.

Since the query method may be called many times with different word pairs, the class should be designed to answer each query efficiently.

You may assume both query words always exist in the original list, and the two query words are never equal.

Class Definition

Implement the class ShortestWordDistance.

Constructor

ShortestWordDistance(List<String> words)

Initializes the object using the given list of words.

Method Signature

int shortest(String word1, String word2)

Returns the minimum distance between any occurrence of word1 and any occurrence of word2 in the original list.

Deterministic Output Rule

The output is always deterministic because the method returns a single integer: the minimum possible index distance between the two given words.

Constraints

  • 1 ≤ words.size() ≤ 100,000
  • 1 ≤ words[i].length() ≤ 100
  • word1 != word2
  • word1 and word2 are both present in words
  • The method shortest may be called repeatedly many times.
  • All words contain only lowercase English letters.

Examples

Example 1

Input
ShortestWordDistance(words = ["alpha", "beta", "gamma", "alpha", "delta", "beta"])
shortest(word1 = "alpha", word2 = "delta")

Output
1

Explanation
The word "alpha" appears at indices 0 and 3, and "delta" appears at index 4. The shortest distance is |3 - 4| = 1.

Example 2

Input
ShortestWordDistance(words = ["alpha", "beta", "gamma", "alpha", "delta", "beta"])
shortest(word1 = "beta", word2 = "gamma")

Output
1

Explanation
The word "beta" appears at indices 1 and 5, and "gamma" appears at index 2. The shortest distance is |1 - 2| = 1.

Example 3

Input
ShortestWordDistance(words = ["red", "blue", "green", "yellow", "blue", "red", "green"])
shortest(word1 = "yellow", word2 = "red")

Output
2

Explanation
The word "yellow" appears at index 3, and "red" appears at indices 0 and 5. The shortest distance is |3 - 5| = 2.




Please use Laptop/Desktop or any other large screen to add/edit code.