Show problems as
Classic problem #243EasyArrayString

Shortest Word Distance

Real-world version: Closest Station Calls in the Announcement Log
Tracked in this browser only
Read Shortest Word Distance on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

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.

Examples

Example 1

Input
wordsDict = ["fen", "ash", "cwm", "ash", "bly", "ash", "fen"], word1 = "fen", word2 = "bly"
Output
2

"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

Input
wordsDict = ["mo", "mo", "ka", "ka", "ze"], word1 = "mo", word2 = "ze"
Output
3

"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

Input
wordsDict = ["elm", "dun"], word1 = "dun", word2 = "elm"
Output
1

"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.

Constraints

  • 2 <= wordsDict.length <= 3 * 10^4
  • 1 <= wordsDict[i].length <= 10
  • wordsDict[i] contains only lowercase English letters.
  • word1 and word2 both appear in wordsDict.
  • word1 != word2

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def shortest_distance(wordsDict: list[str], word1: str, word2: str) -> int:
Java
public int shortestDistance(String[] wordsDict, String word1, String word2)