Practice/LinkedIn/Leetcode 243. Shortest Word Distance
CodingOptional
You are given an array of strings and two different target words that both exist within the array. Your task is to find the minimum distance between any occurrence of the first word and any occurrence of the second word.
The distance between two words is defined as the absolute difference between their indices in the array.
Both target words are guaranteed to exist in the array and are guaranteed to be different from each other.
word1 and any occurrence of word2Example 1:
Input: words = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice" Output: 3 Explanation: "coding" appears at index 3 and "practice" appears at index 0. The distance is |3 - 0| = 3.
Example 2:
Input: words = ["a", "c", "b", "a"], word1 = "a", word2 = "b" Output: 1 Explanation: "a" appears at indices 0 and 3. "b" appears at index 2. The minimum distance is min(|0 - 2|, |3 - 2|) = 1.
Example 3:
Input: words = ["hello", "world", "hello"], word1 = "hello", word2 = "world" Output: 1 Explanation: "hello" appears at indices 0 and 2. "world" appears at index 1. The minimum distances are |0 - 1| = 1 and |2 - 1| = 1.