Skip to content

Commit a98d5ad

Browse files
committed
find pivot index
1 parent fbb9385 commit a98d5ad

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

724.FindPivotIndex.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
"""
2+
724. Find Pivot Index
3+
Easy
4+
Array | Prefix Sum
5+
---
6+
Given an array of integers nums, calculate the pivot index of this array.
7+
8+
The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to
9+
the sum of all the numbers strictly to the index's right.
10+
11+
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.
12+
This also applies to the right edge of the array.
13+
Return the leftmost pivot index. If no such index exists, return -1.
14+
15+
Example 1:
16+
Input: nums = [1,7,3,6,5,6]
17+
Output: 3
18+
Explanation:
19+
The pivot index is 3.
20+
Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
21+
Right sum = nums[4] + nums[5] = 5 + 6 = 11
22+
23+
Example 2:
24+
Input: nums = [1,2,3]
25+
Output: -1
26+
Explanation:
27+
There is no index that satisfies the conditions in the problem statement.
28+
29+
Example 3:
30+
Input: nums = [2,1,-1]
31+
Output: 0
32+
Explanation:
33+
The pivot index is 0.
34+
Left sum = 0 (no elements to the left of index 0)
35+
Right sum = nums[1] + nums[2] = 1 + -1 = 0
36+
37+
Constraints:
38+
1 <= nums.length <= 104
39+
-1000 <= nums[i] <= 1000
40+
41+
Note: This question is the same as 1991: https://leetcode.com/problems/find-the-middle-index-in-array/
42+
"""
43+
44+
from typing import List
45+
46+
47+
# O(n) time | O(1) space
48+
class Solution:
49+
def pivotIndex(self, nums: List[int]) -> int:
50+
left, right = 0, sum(nums)
51+
for (idx, num) in enumerate(nums):
52+
right -= num
53+
if left == right:
54+
return idx
55+
left += num
56+
return -1

0 commit comments

Comments
 (0)