Question:
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"]
.
1 | Input: word1 = “coding”, word2 = “practice” |
1 | Input: word1 = "makes", word2 = "coding" |
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
Analysis:
This one is pretty straightforward. You can use two different word indices to represent word1 and word2 by given a single for-loop to find out these two different indices. The difference between these two indices would be the distance between word1 and word2. You need to compare different distances to get the shortest one. That one would be our answer. So, the runtime complexity would be O(n)
because you need to run through all elements in this word dictionary. And, the space complexity would be O(1)
because we only need three variables to memorize the word indices and the result.
1 | class Solution { |