Skip to content
ΣDSA Patterns
Menu
Language

Prefix Sum

Guide 4 of 6 · Path 4 of 6

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Find Pivot Index

Problem (restated)

Return the leftmost pivot index where sum of left elements equals sum of right elements, or -1.

Intuition

Total sum is fixed; as you walk, leftSum grows and rightSum = total, leftSum, nums[i].

Approaches

Running left sum

Tested only
Time O(n)Space O(1)

Idea. Compute total. For each i, if leftSum == total, leftSum, nums[i], return i. Else leftSum += nums[i].

Walkthrough. [1,7,3,6,5,6] → pivot at index 3 (1+7+3 = 5+6).

Trade-offs. Prefix arrays use O(n) space; running sum is enough.

Solution
export function pivotIndex(nums: number[]): number {
  const total = nums.reduce((a, b) => a + b, 0);
  let left = 0;
  for (let i = 0; i < nums.length; i++) {
    if (left === total - left - nums[i]!) return i;
    left += nums[i]!;
  }
  return -1;
}
export function pivotIndex(nums: number[]): number {
  const total = nums.reduce((a, b) => a + b, 0);
  let left = 0;
  for (let i = 0; i < nums.length; i++) {
    if (left === total - left - nums[i]!) return i;
    left += nums[i]!;
  }
  return -1;
}

Reflection