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

  1. Compute the total sum once. Then walk left to right, maintaining left_sum.
  2. The right sum at index i is total - left_sum - nums[i], since the total includes both sides plus the pivot itself.
  3. Return i as soon as left_sum == total - left_sum - nums[i].
  4. 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], so total - left alone 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.