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

Leetcode Problem 244. Shortest Word Distance II

244. Shortest Word Distance II

Leetcode Solutions

Using Preprocessed Sorted Indices

  1. Initialize a dictionary to store the list of indices for each word in the input array.
  2. Iterate over the input array and populate the dictionary with the word as the key and its indices as the value.
  3. For the shortest method, retrieve the sorted lists of indices for both word1 and word2 from the dictionary.
  4. Initialize two pointers, i and j, to iterate over the two lists of indices.
  5. While both pointers are within the bounds of their respective lists, calculate the current distance and update the minimum distance if the current is smaller.
  6. Increment the pointer which points to the smaller index value to potentially find a closer match.
  7. Continue until one of the lists is fully traversed.
  8. Return the minimum distance found.
UML Thumbnail

Brute Force Approach

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...