Trains the technique from
LeetCode 243Shortest Word DistanceThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A train's public-address unit keeps a log of the station codes it has called out, one code per entry, in the order they were announced. The log arrives as wordsDict, so wordsDict[i] is the code called at position i. A code may be called many times.
Given two different codes word1 and word2, both of which appear somewhere in the log, return the smallest possible value of |i - j| over positions i holding word1 and positions j holding word2.
Example 1
"fen" sits at positions 0 and 6, and "bly" sits at position 4. The gaps available are 4 and 2, so the answer is 2.
Example 2
"mo" sits at positions 0 and 1 and "ze" sits at position 4, giving gaps of 4 and 3, so the answer is 3.
Example 3
"dun" is at position 1 and "elm" is at position 0. The gap is measured without regard to which came first, so it is 1.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def shortest_distance(wordsDict: list[str], word1: str, word2: str) -> int:public int shortestDistance(String[] wordsDict, String word1, String word2)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.