245. Shortest Word Distance III
Approach 1: Storing list of indices of both words
For both the words we store the indices of all the positions they occur in. Once we have that we can easily iterate through both of these individual lists and find the minimum difference
Time Complexity: O(N^2)
Space Complexity: O(N)
Approach 2: Iterating through list but storing only last seen index of each word
In this approach instead of storing lists of indices we just need to store the last seen one. Each time we see one of the words we just calculate the difference between the two last seen indices and update it if it smaller than the shortest distance we've seen before
Time Complexity: O(N)
Space Complexity: O(1)
Last updated