BackeasyArraysHCL

Array Pivot Index Solution

Problem Statement

Given a sequence of integers, identify the index of the pivot element. A pivot index is defined as a position where the arithmetic sum of all elements strictly preceding the index is identical to the arithmetic sum of all elements strictly following the index. The value at the pivot index itself is excluded from both the left-hand and right-hand summations.

If multiple indices satisfy this equilibrium condition, return the smallest such index. If no index in the array meets the criteria, return -1.

The input is provided as a one-dimensional array of integers. The output must be a single integer representing the pivot index or -1 if the array is unbalanced at every position.

Example 1
Input
nums = [1, 7, 3, 6, 5, 6]
Output
3

Explanation: Total sum is 28. At index 3 (value 6), the sum of elements to the left (1 + 7 + 3) is 11. The sum of elements to the right (5 + 6) is 11. Since 11 equals 11, index 3 is the pivot.

Example 2
Input
nums = [2, 4, 1, 3, 5]
Output
-1

Explanation: Total sum is 15. Index 0: Left sum 0, Right sum 13. Index 1: Left sum 2, Right sum 9. Index 2: Left sum 6, Right sum 8. Index 3: Left sum 7, Right sum 5. Index 4: Left sum 10, Right sum 0. No index has equal left and right sums.

Example 3
Input
nums = [0, 0, 0, 0]
Output
0

Explanation: Total sum is 0. At index 0, the sum of elements to the left is 0 (empty set). The sum of elements to the right is 0 + 0 + 0 = 0. Since 0 equals 0, index 0 is the pivot. As it is the first valid index, it is returned.

Example 4
Input
nums = [-1, 2, -3, 4, -5]
Output
-1

Explanation: Total sum is -3. At index 2 (value -3), the sum of elements to the left (-1 + 2) is 1. The sum of elements to the right (4 + -5) is -1. Wait, 1 != -1. Let's re-calculate. Left of 2: -1+2=1. Right of 2: 4-5=-1. Not equal. Let's check index 1. Left: -1. Right: -3+4-5=-4. Not equal. Let's check index 3. Left: -1+2-3=-2. Right: -5. Not equal. Let's check index 0. Left: 0. Right: 2-3+4-5=-2. Not equal. Let's check index 4. Left: -1+2-3+4=2. Right: 0. Not equal. Actually, let's use a better example for negative numbers. Input: [-1, 2, -3, 4, -5] doesn't work. Let's try [-2, 1, 3, -2, 4]. Sum=4. Index 0: L=0, R=6. Index 1: L=-2, R=5. Index 2: L=-1, R=2. Index 3: L=2, R=4. Index 4: L=0, R=0. So index 4 is pivot. Let's use that.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • The sum of all elements in the array will fit within a 64-bit integer.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Array Pivot Index — Problem Statement & Solution Guide

ArraysEasyPrefix Sum
TimeO(n)
|
SpaceO(1)

Problem Description

Given a sequence of integers, identify the index of the pivot element. A pivot index is defined as a position where the arithmetic sum of all elements strictly preceding the index is identical to the arithmetic sum of all elements strictly following the index. The value at the pivot index itself is excluded from both the left-hand and right-hand summations.

If multiple indices satisfy this equilibrium condition, return the smallest such index. If no index in the array meets the criteria, return -1.

The input is provided as a one-dimensional array of integers. The output must be a single integer representing the pivot index or -1 if the array is unbalanced at every position.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Array Pivot Index"

easy

WHY DOES IT MATTER?

Understanding prefix‑sum patterns lets engineers solve a wide class of equilibrium and balance problems efficiently, turning seemingly nested‑loop challenges into linear scans.

OPTIMIZATION CHALLENGE

The key insight is that the right‑hand sum can be expressed as totalSum - leftSum - currentElement, allowing us to compute both sides on the fly without recomputing sums for each index.

REAL-WORLD CONNECTION

Think of a load‑balancing router that must decide where to split traffic: the total incoming bandwidth is fixed, and the router seeks a point where the cumulative load before the split equals the load after, mirroring the pivot index logic.

During an interview, compute totalSum first, then iterate while updating leftSum; if leftSum equals totalSum - leftSum - nums[i], you have a pivot—this one‑pass mental model is quick to articulate and implement.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(1)

Core Theory — Why This Approach?

The pivot index problem is a classic example of prefix‑sum reasoning. A naive solution would recompute the sum of elements to the left and right of each candidate index, leading to O(n²) time on large inputs because each sum traversal repeats work already done for previous indices. The optimal paradigm leverages the fact that the total sum of the array is constant; by maintaining a running left‑sum while iterating once through the array, the right‑sum can be derived as totalSum - leftSum - currentElement. This transforms the problem into a single linear scan, eliminating redundant calculations and achieving O(n) time with O(1) extra space.

The underlying algorithmic pattern is often called "running total" or "prefix sum" and is foundational for many array‑based problems such as subarray sums, equilibrium points, and range queries. Recognizing that the left and right aggregates are complementary parts of a fixed total enables the reduction from quadratic to linear complexity, which is crucial when the input size can reach 10⁵ or more. Moreover, this approach is cache‑friendly and works in-place, making it suitable for memory‑constrained environments typical in production services.

Interview Questions on This Problem

Q1How would you modify the solution to return all pivot indices instead of just the first one?

Maintain the same linear scan, but instead of returning immediately when a pivot is found, push the index into a result list and continue scanning; the overall complexity remains O(n) time and O(k) space where k is the number of pivots.

Q2Can you solve the pivot index problem without using extra variables for total sum, i.e., in a single pass without pre‑computing the total?

Yes, by first computing the total sum in a preliminary pass (still O(n)) and then performing the second pass for pivot detection; the two passes together still constitute linear time and O(1) extra space, which is acceptable in interview settings.

Q3How would the algorithm change if the array could contain very large integers that might overflow a 32‑bit integer?

Use a 64‑bit integer type (e.g., long long in C++ or long in Java) for the running sums and total sum to avoid overflow, ensuring that arithmetic stays accurate even when individual elements are near the integer limits.

Examples

Example 1

Input

nums = [1, 7, 3, 6, 5, 6]

Output

3

Explanation: Total sum is 28. At index 3 (value 6), the sum of elements to the left (1 + 7 + 3) is 11. The sum of elements to the right (5 + 6) is 11. Since 11 equals 11, index 3 is the pivot.

Example 2

Input

nums = [2, 4, 1, 3, 5]

Output

-1

Explanation: Total sum is 15. Index 0: Left sum 0, Right sum 13. Index 1: Left sum 2, Right sum 9. Index 2: Left sum 6, Right sum 8. Index 3: Left sum 7, Right sum 5. Index 4: Left sum 10, Right sum 0. No index has equal left and right sums.

Example 3

Input

nums = [0, 0, 0, 0]

Output

0

Explanation: Total sum is 0. At index 0, the sum of elements to the left is 0 (empty set). The sum of elements to the right is 0 + 0 + 0 = 0. Since 0 equals 0, index 0 is the pivot. As it is the first valid index, it is returned.

Example 4

Input

nums = [-1, 2, -3, 4, -5]

Output

-1

Explanation: Total sum is -3. At index 2 (value -3), the sum of elements to the left (-1 + 2) is 1. The sum of elements to the right (4 + -5) is -1. Wait, 1 != -1. Let's re-calculate. Left of 2: -1+2=1. Right of 2: 4-5=-1. Not equal. Let's check index 1. Left: -1. Right: -3+4-5=-4. Not equal. Let's check index 3. Left: -1+2-3=-2. Right: -5. Not equal. Let's check index 0. Left: 0. Right: 2-3+4-5=-2. Not equal. Let's check index 4. Left: -1+2-3+4=2. Right: 0. Not equal. Actually, let's use a better example for negative numbers. Input: [-1, 2, -3, 4, -5] doesn't work. Let's try [-2, 1, 3, -2, 4]. Sum=4. Index 0: L=0, R=6. Index 1: L=-2, R=5. Index 2: L=-1, R=2. Index 3: L=2, R=4. Index 4: L=0, R=0. So index 4 is pivot. Let's use that.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • The sum of all elements in the array will fit within a 64-bit integer.

Optimal Approach & Strategy

First compute the total sum of the array. Then iterate once, maintaining a running left sum; the right sum is derived as total - leftSum - currentElement. Compare left and right sums at each step to locate the pivot.

Brute Force Approach

For each index, sum all elements to its left and all elements to its right, then compare the two sums. This requires O(n) work per index, leading to O(n²) total time.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function pivotIndex(nums) {
    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;
}

const nums = [1, 7, 3, 6, 5, 6];
const index = pivotIndex(nums);
console.log(index);

Asked in Top Tech Interviews

HCL

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.