Home > database >  Problem with optimization leet code time exceeded
Problem with optimization leet code time exceeded

Time:12-08

The question is from Leetcode as follows: Given an array of integers nums, calculate the pivot index of this array.

The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.

If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.

Return the leftmost pivot index. If no such index exists, return -1.

Example 1:

Input: nums = [1,7,3,6,5,6]

Output: 3

Explanation: The pivot index is 3. Left sum = nums[0] nums[1] nums[2] = 1 7 3 = 11 Right sum = nums[4] nums[5] = 5 6 = 11

Example 2:

Input: nums = [1,2,3]

Output: -1

Explanation: There is no index that satisfies the conditions in the problem statement.

Example 3:

Input: nums = [2,1,-1]

Output: 0

Explanation: The pivot index is 0. Left sum = 0 (no elements to the left of index 0) Right sum = nums[1] nums[2] = 1 -1 = 0

My solution works but exceeds the Leetcode time limit. Reached test case 740/745 How would I go about further optimizing the code?

class Solution:
def pivotIndex(self, nums: List[int]) -> int:
    left_list = []
    for index,num in enumerate(nums):
        if sum(nums[index 1:]) == sum(left_list):
            return index
        else:
            left_list.append(num)
    return -1

CodePudding user response:

you don't need to do multiple sums, you only need to do a cumulative sum, then each iteration you can use it to calculate the sum of the right half by subtracting the left sum.

from itertools import accumulate
from operator import add
from typing import List

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        cumsum = accumulate(nums, add)
        final_sum = sum(nums)
        last_sum = 0  # to skip summing the current element in evaluation.
        for index, left_sum in enumerate(cumsum):
            right_sum = final_sum - left_sum
            if last_sum == right_sum:
                return index
            last_sum = left_sum
            
        return -1


inputs = [1,7,3,6,5,6]
print(Solution().pivotIndex(inputs))
# 3

CodePudding user response:

Continually summing slices from the list is going to be very inefficient. You need a different strategy. Something like this:

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        total = sum(nums)
        left = 0
        for i, x in enumerate(nums):
            if left == total - left - x:
                return i
            left  = x
        return -1
  • Related