Python O(N) Solution O(1) Space


  • 0
    class Solution(object):
        def shortestDistance(self, words, word1, word2):
            p1 = p2 = -1
            min_dist = sys.maxint
            for i, word in enumerate(words):
                if words[i] == word1:
                    p1 = i
                if words[i] == word2:
                    p2 = i
                if p1 != -1 and p2 != -1:
                    min_dist = min(min_dist, abs(p1-p2))
            return min_dist
    

  • 0
    N
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.