Shortest Word Distance
Real-world version: Closest Station Calls in the Announcement LogThe 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.
def shortest_distance(wordsDict: list[str], word1: str, word2: str) -> int:public int shortestDistance(String[] wordsDict, String word1, String word2)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Longest Common PrefixReal-world version: Shared Crate CodeEasy
- Verifying an Alien DictionaryReal-world version: Catalogue Order Under a Custom Glyph SequenceEasy
- Find Common CharactersReal-world version: Tiles Every Rack Can SupplyEasy
- Destination CityReal-world version: Last Stop On The Courier RunEasy