Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading