NeetCode #51LC-724EasyArrays & Hashing
← Back to All Problems#51 · #724 · Find Pivot Index(寻找数组的中心下标)
📌 Problem Statement & Constraints
Given an array of integers
nums, return the leftmost pivot index where the sum of all elements strictly to the left equals the sum of all elements strictly to the right. If no such index exists, return -1. Constraints: 1 <= nums.length <= 10^4, -1000 <= nums[i] <= 1000.💡 Core Algorithmic Approaches
- Compute the total sum once. Then walk left to right, maintaining
left_sum. - The right sum at index
iistotal - left_sum - nums[i], since the total includes both sides plus the pivot itself. - Return
ias soon asleft_sum == total - left_sum - nums[i]. - Scanning left to right automatically gives the leftmost pivot, which the problem requires when several exist.
💻 Benchmark Python3 Implementation
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
total = sum(nums)
left = 0
for i, x in enumerate(nums):
# right = total - left - x
if left == total - left - x:
return i # leftmost pivot wins by construction
left += x
return -1⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass to compute the total and one pass to find the pivot.
💾 Space Complexity
O(1): a running left sum plus the total.
⚠️ Interview Pitfalls & Follow-ups
- Forgetting to subtract the pivot itself: the right sum excludes
nums[i], sototal - leftalone is wrong. - Scanning right to left: that would return the rightmost pivot, but the problem asks for the leftmost.
- Building prefix and suffix arrays: O(n) extra space for no benefit; the running sum is enough.
- Handling the boundaries: index 0 has an empty left side (sum 0), and the last index has an empty right side -- both are covered by the formula with no special cases.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
寻找数组的中心下标
给你一个整数数组 nums,请计算数组的 中心下标 。数组中心下标是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。如果中心下标位于数组最左端,那么左侧数之和视为 0;位于最右端同理。如果数组有多个中心下标,应该返回 最靠近左边 的那一个;如果不存在,返回 -1。约束:1 ≤ nums.length ≤ 10^4;-1000 ≤ nums[i] ≤ 1000。
核心要点
- 总和 + 滚动左和(标准解) :先求数组总和 total。再从左到右遍历,维护 left(当前位置左侧元素之和)。
- 判定条件 :位置 i 是中心下标当且仅当 left == total - left - nums[i] ,即「左侧和 == 右侧和」。
- 为什么先算 total :右侧和可以通过 total - left - nums[i] 在 O(1) 内得到,避免每次重新求和。
- 返回最左的 :从左往右遍历,第一个满足条件的位置即为答案,直接返回。
常见陷阱
- 每次重新求右侧和 :退化为 O(n²)。必须利用「右侧和 = total − left − nums[i]」的 O(1) 推导。
- 先 left += x 再判定 :会导致判定时把当前元素算进左侧,条件错误。必须 先判定、后累加 。
- 忘记处理边界 :下标 0 时 left = 0,若右侧和也为 0 则返回 0;本解天然正确。
- 误以为要返回最右的中心下标 :题目明确要求返回 最左 的,因此从左往右第一个满足即返回。
参考实现
class Solution:
def pivotIndex(self, nums: list[int]) -> int:
total = sum(nums)
left = 0
for i, x in enumerate(nums):
# 右侧和 = 总和 - 左侧和 - 当前元素
if left == total - left - x:
return i
left += x
return -1