educative.io

Educative

Another interesting solution... which works in LeetCode but for some reason doesn't work here :)

When I was solving the same TwoSum question on LeetCode, I once saw interesting approach - using the dictionary with the difference between “target” number and current number in a cycle being a key, and the index of that number - as a value.
Looks like that:

def find_sum(lst, k):
    dicc = {}
    for i in range(len(lst)):
        ost = k - lst[i]
        if ost not in dicc:
            dicc[lst[i]] = i
        else:
            return [dicc[ost], i]

but the same approach (with different variable names) is correct for the leetcode problem, but gives wrong result here. Can’t understand why.


Course: https://www.educative.io/courses/data-structures-in-python
Lesson: Educative: Interactive Courses for Software Developers