Home > Net >  twosum leetcode problem, why this solution doesn't work? "Index out of range"
twosum leetcode problem, why this solution doesn't work? "Index out of range"

Time:11-11

The problem give an array of integers 'nums' and an integer 'target', return indices of the two numbers such that they add up to target.

Example:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0]   nums[1] == 9, we return [0, 1].
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        y=0
        x=0
        solutions = []
        for x in nums:
            for y in nums:
                if (nums[x]   nums [y]) == target:
                    solutions[0] = x
                    solutions[1] = y
                    print(solutions)
                    break
                y =1
            x =1

Why this solution doesn't work? The problem is "Index out of range" in line 8

CodePudding user response:

When you do for x in nums you actually iterate over values, not indices, so then nums[x] is actually x[2], then x[7] - which is out of range of the list.

Try for x in range(0, len(nums)) instead, same goes for y.

Or, you can also keep iterating over values and just do if (x y) == target.

CodePudding user response:

Not pretty but it works:

def two_sum(nums, target):
    for idx, val in enumerate(nums):
        if(idx < len(nums)-1 and nums[idx]   nums[idx 1] == target):
            print (idx, idx 1)

two_sum([2,7,11,15],9)

Hope it helps and enjoy programming

  • Related