filmov
tv
Coding Challenge from Leetcode - Shortest Word Distance!
![preview_player](https://i.ytimg.com/vi/e48slU28qNI/maxresdefault.jpg)
Показать описание
Problem:
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.
Solution summary:
— Intuition / tip: “Two pointer” solution
— Initialize two pointer variables to keep track of the latest indexes of word1 and word2; initially set them to -1
— Initialize a variable to keep track of the minimum distance result; set to the length of the word list
— Loop through the word list
— For each word, check if the word is equal to word1 or word2, updating the respective variable to keep track of the latest index
— For each word, check if the latest word1 and word2 indexes are set (not -1)
— If so, then calculate the current distance between word1 and word2 indexes, then set the minimum distance variable to this if it is a new low
— After looping the word list, return the minimum distance variable as the result
— Time complexity: O(n * m) where ’n’ is the number of elements of the
— Space complexity: O(1)
Let me know if you have any questions or see ways I could have optimized!
Let's connect!
Get my coding gear / desk setup 👨🏾💻