EmJee
EmJee

Reputation: 13

Two Sum LeetCode - why my own code failed

Problem:

Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.


My code:

def twoSum(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    for x in nums:
        for y in nums: 
            if nums.index(x) != nums.index(y) and x + y == target :
                    return [nums.index(x), nums.index(y)]

 print (twoSum ([3, 3],6))

Output:

null

In my mind the first "iteration" (I am not quite sure if this is the right term) looks like :

If 0 != 0 (False) and 3 + 3= 6 (True)  --> as  the first condition is not met, the y loops

So the next iteration looks like:

If 0 != 1 (True) and 3 + 3 = 6 (True) 

--> as above conditions are met, the function would return [0,1], but instead the code actually returns null and I do not understand the reason.

So, I would really appreciate, if someone could either explain what's happening, or tell me some keywords, in order to search for the answer on my own :)

Upvotes: 1

Views: 888

Answers (3)

Kushagra Gupta
Kushagra Gupta

Reputation: 614

I think since both the elements in [3,3] are same, hence nums.index(x) and nums.index(y) always give 0 which is equal hence the if-block never execute.

def twoSum(self, nums, target):
  for x in range(len(nums)):
    for y in range(len(nums)): 
        if x != y and nums[x] + nums[y] == target :
                return [x, y]
print (twoSum ([3, 3],6))

this is my solution.

Upvotes: 0

John Gordon
John Gordon

Reputation: 33359

As MoxieBall pointed out, your code returns None because .index() returns the index of the first matching value.

You can use enumerate() to get the true index location:

for x_index, x_value in enumerate(nums):
    for y_index, y_value in enumerate(nums):
        if x_index != y_index and x_value + y_value == target:
            return [x_index, y_index]

Upvotes: 2

MoxieBall
MoxieBall

Reputation: 1916

The index method will find the index of the first occurrence in the list. Since your list has the same number twice, no call to index in your code as written will ever return anything except 0. Thus, if nums.index(x) != nums.index(y) is never True so your function returns None.

Upvotes: 0

Related Questions