Leetcode!
  • LeetCode!
  • My personal guide to Leetcode
  • Array
    • 11. Container With Most Water
    • 15. 3Sum
    • 219. Contains Duplicate II
    • 238. Product of Array Except Self
    • 245. Shortest Word Distance III
    • 392. Is Subsequence
    • 442. Find All Duplicates in an Array
    • 561. Array Partition I
    • 661. Image Smoother
    • 697. Degree of an Array
    • 723. Candy Crush
    • 832. Flipping an Image
  • Backtracking
    • 294. Flip Game II
    • 401. Binary Watch
    • 1079. Letter Tile Possibilities
  • Binary Search
    • 744. Find Smallest Letter Greater Than Target
    • 852. Peak Index in a Mountain Array
  • String
    • 6. ZigZag Conversion
    • 17. Letter Combinations of a Phone Number
    • 38. Count and Say
    • 521. Longest Uncommon Subsequence I
    • 544. Output Contest Matches
    • 937. Reorder Data in Log Files
  • Design
    • 251. Flatten 2D Vector
    • 281. Zigzag Iterator
  • Hash Table
    • 1. Two Sum
    • 508. Most Frequent Subtree Sum
    • 884. Uncommon Words from Two Sentences
    • 734. Sentence Similarity
  • Linked List
    • 2. Add Two Numbers
  • Unsorted
    • 917. Reverse Only Letters
  • Math
    • 43. Multiply Strings
    • 462. Minimum Moves to Equal Array Elements II
    • 553. Optimal Division
    • 800. Similar RGB Color
  • Greedy
    • 406. Queue Reconstruction by Height
    • 861. Score After Flipping Matrix
  • Tree
    • 701. Insert into a Binary Search Tree
    • 897. Increasing Order Search Tree
  • Divide and Conquer
    • 53. Maximum Subarray
  • Dynamic Programming
    • 62. Unique Paths
    • 63. Unique Paths II
    • 64. Minimum Path Sum
    • 120. Triangle
    • 198. House Robber
    • 213. House Robber II
    • 303. Range Sum Query - Immutable
    • 518. Coin Change 2
    • 750. Number Of Corner Rectangles
    • 337. House Robber III
  • Depth first search
    • 841. Keys and Rooms
  • Trie
    • 677. Map Sum Pairs
  • Two pointer
    • 42. Trapping Rain Water
Powered by GitBook
On this page
  • Approach 1: Storing list of indices of both words
  • Approach 2: Iterating through list but storing only last seen index of each word
  1. Array

245. Shortest Word Distance III

Approach 1: Storing list of indices of both words

class Solution(object):
    def shortestWordDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        word1s = []
        word2s = []
        for i in range(len(words)):
            if words[i] == word1:
                word1s.append(i)
            if words[i] == word2:
                word2s.append(i)
        mi = float('inf')
        for i in word1s:
            for j in word2s:
                if i != j:
                    mi = min(abs(i-j), mi)
        return mi

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

class Solution(object):
    def shortestWordDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        idx1 = idx2 = res = float('inf')
        if word1 == word2:
            for i,word in enumerate(words):
                if word == word1:
                    idx1 = idx2 
                    idx2 = i
                    res = min(res,abs(idx2-idx1))
        else:
            for i,word in enumerate(words):
                if word == word1:
                    idx1 = i
                    res = min(res,abs(idx1-idx2))
                elif word == word2:
                    idx2 = i
                    res = min(res,abs(idx1-idx2))
        return res

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)

Previous238. Product of Array Except SelfNext392. Is Subsequence

Last updated 6 years ago