alyse
alyse

Reputation: 43

TwoSum solution only works for one input

I am a beginner, and for some reason my method below is wrong. The first input yields a right answer but not the second. The question is: Given an array of integers, return indices of the two numbers such that they add up to a specific target.

class Solution(object):
    def twoSum(self, nums, target):
        for i in nums:
            for j in nums:
                if i+j == target or j+i == target:
                    indexi = nums.index(i)
                    indexj = nums.index(j)
                    return [indexi, indexj]

Your input
 [2,7,11,15]
     9
 [3,2,4]
     6
Output
  [0,1]
  [0,0]
Expected
  [0,1]
  [1,2]

Upvotes: 0

Views: 59

Answers (2)

NumberC
NumberC

Reputation: 596

The problem was that it added the first index twice. Your code doesn't prohibit the software from doing this. You should instead try:

for i in len(nums):
            for j in len(nums):
                if i != j and nums[i] + nums[j] == target:
                    return [i, j]

This checks that you're not adding the index to itself.

Upvotes: 0

Robin Zigmond
Robin Zigmond

Reputation: 18249

The problem that's happening in your second example is that i and j can be the same number - as both loop over the nums array independently.

A simple way to avoid this is to loop over the indices, and start j from after i. This will also avoid going over each pair twice:

def twoSum(self, nums, target):
    for i in range(0, len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i]+nums[j] == target:
                return [i, j]

(Note that I've also removed the pointless checking of the same thing twice in the if statement. I also don't see why this needs to be a method of a class, as opposed to a regular function, since self is not referred to anywhere. But it might make sense depending on what the rest of your class does, which you don't share.)

Upvotes: 2

Related Questions