Search code examples
pythonsum

Modification of Leetcode 'Two Sum' question


Just tried to modify the leetcode 'Two Sum' problem to have the output as: 'the index of the very first number' + 'the index of the remaining no which adds up to the target'

index of first number ie [0] is always the reference.

Hence, [2,3,4,6,7,8],10 will always be [0,5]

[3,2,5,1,8,90,34,78,23],93 hence [0,5]

Was actually able to achieve by modifying the original solution a bit.

def sumri(num,target):
    seen = {}
    
    for i in range(len(num)):
        diff = target - num[0]
        seen[num[i]] = i
        
        if diff in seen:
            return (seen[num[0]],seen[diff])

However, when I try to put:

        if diff in seen:
            return (seen[num[0]],seen[diff])
        else:
            return 'sorry nothing adds up after 0'

The output in every case goes to else. What am I missing?

Tried without including the else, works fine. I am just trying to find out why the execution directly goes to else even after it finds the relevant number in the arr.


Solution

  • With your modification, your code will always execute a return in the first iteration of the loop. You cannot know whether the answer is negative unless you have made all iterations of the loop.

    The fix is straightforward: put that return statement after the loop. If execution gets there it means the if condition was never true, not in any iteration of the loop:

    def sumri(num,target):
        seen = {}
        
        for i in range(len(num)):
            diff = target - num[0]
            seen[num[i]] = i
            
            if diff in seen:
                return (seen[num[0]],seen[diff])
    
        return 'sorry nothing adds up after 0'