Shortest Word Distance
Easy
Given a list of words and two wordsword1_and_word2, return the shortest distance between these two words in the list.
Example:
Assume that words =["practice", "makes", "perfect", "coding", "makes"]
.
Note: You may assume that word1 does not equal to word2, and _word1 _and _word2 _are both in the list.
Solution
One pass - O(n) time, O(1) space
We can greatly improve on the brute-force approach by keeping two indices i1 and i2 where we store the most recent locations of word1 and word2. Each time we find a new occurrence of one of the words, we do not need to search the entire array for the other word, since we already have the index of its most recent occurrence.
Reference
https://leetcode.com/problems/shortest-word-distance/solution/
Last updated