Python Solution O(1) Space O(n) Time

  • 0
    class Solution(object):
        def shortestDistance(self, words, word1, word2):
            a, b = sys.maxint, -sys.maxint
            mind = sys.maxint
            for i in range(len(words)):
                if words[i] == word1:
                    a = i
                elif words[i] == word2:
                    b = i
                mind = min(mind, abs(a-b))
            return mind

Log in to reply

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