why does a list of size two not work with this nested for loop

Issue

For the Two Sum problem on LeetCode, it says:

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

Input: nums = [2,7,11,15], target = 9
Input: nums = [3,2,4], target = 6
Input: nums = [3,3], target = 6

The output for all three problems would be:

[0,1]
[1,2]
[0,1]

But for some reason my code fails the last test case and prints out:

[0,1]
[1,2]
[]

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        temp = 0
        tempValue = 0
        for x in nums:  # x is 3
            temp = target - x  # temp is 3
            for y in nums:  # y is 3
                if nums.index(x) != nums.index(y):
                    tempValue = x + y  # 3+3 = 6
                    
                    if tempValue == target:
                        return [nums.index(x), nums.index(y)]
            

Solution

You have a lot of boilerplate in your code. You should avoid unnecesary temporary variables and use enumerate with array indexing to get the index.

You need two for loops on your code. One will iterate over the full list and the second one will iterate the full list but starting on the next position of value evaluated from the first loop.

The code:

def two_sum(nums: list[int], target: int) -> list[int]:
    for i, x in enumerate(nums):
        for j, y in enumerate(nums[i+1:]):
            if x + y == target:
                return [i, j+i+1]

Your code fails because:

if nums.index(x) != nums.index(y):

is always false in the case 3. x and y are both 3 always and the index is always 0.

Answered By – Fran Arenas

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published