Search code examples
arrayspython-3.xdata-structures

Having trouble finding Pivot index


I am trying to get the pivot index of the given array using python in leetcode. for the Given an array of integers nums, calculate the pivot index of this array.

This is the code i've used

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        if 1 <= len(nums) <= 104:
            counter1 = 0
            for i in range(len(nums)):
                if -1000 <= nums[i] <= 1000:
                    counter1 += nums[i]
                    counter2 = 0
                    for j in range(i,len(nums)):
                        counter2+=nums[j]
                    if counter1 == counter2:
                        return i
                else:
                    return -1
        return -1
            

It works with most usecases but i don't understand why it is not working in this specific usecase. this is my submission ( the usecase is present there too) can anyone explain me what i did wrong?


Solution

  • You're checking for the length of the input list being between 1 and 104, but the problem specifies the maximum length as 10 to the power of 4, or 10,000. You are thus returning -1 when the length is greater than 104 without attempting to solve the test case at all.

    So, it should be

    if 1 <= len(nums) <= 10000:
    

    The input for these problems are guaranteed to be valid and conform to the problem specification, so you can also remove the superfluous checks.

    Note that this problem can be solved much faster (in linear time), by precomputing prefix and suffix sums.