243. Shortest Word Distance
Problem description:
Given an array of strings wordsDict
and two different strings that already exist in the array word1
and word2
, return the shortest distance between these two words in the list.
Example 1:
1 | Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice" |
Example 2:
1 | Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding" |
Solution:
Use two variable to track latest index of word1
and word2
. When encounter different word and the we found the word before, update the res
1 | class Solution: |
time complexity: $O()$
space complexity: $O()$
reference:
related problem: