Python, Straightforward with Explanation

  • 6

    Say the lists are A and B. Let Aindex[element] be the index of that element in A. For every index, value pair (j, v) in B, we have some candidate sum-of-indexes i + j, where i = Aindex[v] if it exists. If the candidate sum is better, it becomes our new answer; if the candidate sums are the same, then we append to our answer.

    def findRestaurant(self, A, B):
        Aindex = {u: i for i, u in enumerate(A)}
        best, ans = 1e9, []
        for j, v in enumerate(B):
            i = Aindex.get(v, 1e9)
            if i + j < best:
                best = i + j
                ans = [v]
            elif i + j == best:
        return ans

  • 0
    This post is deleted!

Log in to reply

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