Python 7-lines clean solution

  • 0
            prev, dist = -1, 0
            for curr, word in enumerate(words):
                if word in (word1, word2):
                    if prev != -1 and (word1 == word2 or word1 != word2 and word != words[prev]):
                        dist = min(dist, curr-prev) or curr-prev
                    prev = curr
            return dist

    prev keeps track of last occurance of word1 or word2

Log in to reply

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