[Problem] Find Pivot Index

댕청·2025년 5월 21일

문제 풀이

목록 보기
5/40

leetcode.com/problems/find-pivot-index/

Description

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.

Approach

Simple prefix sum problem that involves creating two lists, one adding up from the left and the other adding up from the right, and we simply return the index where the two equals each other.

Solution

def pivotIndex(self, nums):
    left = [0] + nums[:]
    right = nums[:] + [0]
    print(left, right)
    for i in range(1, len(nums)):
        left[i] += left[i - 1]
        right[len(nums) - i - 1] += right[len(nums) - i]

    print(left, right)
    for i in range(len(nums)):
        if left[i] == right[i + 1]: return i
    return -1
profile
될때까지 모든 걸 다시 한번

0개의 댓글