LeetCode 244, Medium. Topics: Design, Array, Hash Table, Two Pointers, String. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 13 parametrized pytest cases, and a playground notebook:
Problem
Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.
Implement the WordDistance class:
WordDistance(String[] wordsDict) initializes the object with the strings array wordsDict.
int shortest(String word1, String word2) returns the shortest distance between word1 and word2 in the array wordsDict.
Examples
Constraints
1 <= wordsDict.length <= 3 * 10^4
1 <= wordsDict[i].length <= 10
wordsDict[i] consists of lowercase English letters.
word1 and word2 are in wordsDict.
word1 != word2
- At most
5000 calls will be made to shortest.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026