Question:
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
word1 and word2 may be the same, and they represent two individual words in the list.
Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"]
.
1 | Input: word1 = “makes”, word2 = “coding” |
1 | Input: word1 = "makes", word2 = "makes" |
Note:
You may assume word1 and word2 are both on the list.
Analysis:
This quiz is another derived question from Shortest Word Distance.
The most significant difference is that the word1
could be the same as word2
. There is only one edge case you need to consider:
- If the word dictionary has only the same elements, for example, [“ABC”, “ABC”]
Let’s see how to solve this question.
1 | class Solution { |
The time complexity of this class is O(n)
because you need to run through all the elements. The space complexity is O(1)
.