Python solution with detailed explanation


  • 0
    G

    Find Pivot Index https://leetcode.com/problems/find-pivot-index/description/

    Linear Scan with cumulative sum

    • At index idx, the left_sum is sum(nums[0:idx]) and right_rum is sum(nums)-left_sum-nums[idx].
    class Solution(object):
        def pivotIndex(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            ts, cs = sum(nums), 0
            for idx,num in enumerate(nums):
                ls, rs = cs, ts-cs-num
                if ls == rs:
                    return idx
                cs +=num
            return -1
    

Log in to reply
 

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