bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 243. Shortest Word Distance

243. Shortest Word Distance

Leetcode Solutions

One-pass Approach for Finding Shortest Word Distance

  1. Initialize two index variables index1 and index2 to -1, which will hold the most recent positions of word1 and word2 respectively.
  2. Initialize a variable minDistance to Integer.MAX_VALUE to keep track of the shortest distance found so far.
  3. Iterate through the wordsDict array using a variable i.
  4. If the current word is equal to word1, update index1 to i.
  5. If the current word is equal to word2, update index2 to i.
  6. If both index1 and index2 are not -1 (meaning both words have been found at least once), update minDistance with the smaller value between minDistance and the absolute difference between index1 and index2.
  7. After the loop, return minDistance as the result.
UML Thumbnail

Brute Force Approach for Finding Shortest Word Distance

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...