Indeed | OA | Pivot Index
Anonymous User
1298

Question:

# Given a list of integers, write a function that finds the first index in the list such that the sum of
# elements to the left of the index is equal to the sum of elements to the right of the index.
# If no such index is found, return -1. 
# (Note: the index you’re returning should not be included in either sum.)

# Sample Inputs:
#     find_idx([1, 2, 1, 1, 2]) == 2
#     find_idx([-5, 0, 10, -15]) == 1
#     find_idx([5, 6, 7, 8, 9]) == -1

Sol:

def find_idx(cards):
		lsum = 0
        rsum = sum(nums)
        n = len(nums)
        for i in range(0, n):
            rsum -= nums[i]
            if lsum == rsum:
                return i
            lsum += nums[i]
        return -1
		
print(find_idx([1, 2, 1, 1, 2]))
Comments (3)