All problems
0545EasyArrayString

Closest Station Calls in the Announcement Log

Tracked in this browser only
Write code

Trains the technique from

LeetCode 243Shortest Word Distance

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

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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