Simple Python O(n) Time, O(1) Space Solution


  • 0
    R

    First initialize 3 variables: left, mid, right. At the beginning, left = 0, mid = 0, right = sum of the array.
    Next have a index iterate from 0 to length - 1.

    class Solution(object):
        def pivotIndex(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if nums is None or len(nums) <3: return -1
            left, mid, right = 0, 0, sum(nums)
            
            for i in range(len(nums)):
                left += mid
                mid = nums[i]
                right -= nums[i]
                if left == right:
                    return i
            
            return -1
                
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.