Skip to main content

Command Palette

Search for a command to run...

Prefix Sum -2

Published
2 min read
S

Exploring DSA, one problem at a time - learning, coding, and sharing my journey

LeetCode 724 — Find Pivot Index

Author: Sakshi Sharma

After learning the basics of prefix sums in the last blog (Running Sum problem), let’s step a little higher. Today’s problem is LeetCode 724: Find Pivot Index. It’s still beginner-friendly, but it pushes us to think in terms of balancing left and right sums.


Problem in simple words

We need to find an index in the array where the sum of all elements to the left is equal to the sum of all elements to the right. If there are multiple, we return the leftmost one. If no such index exists, return -1.

Example:

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

Because left sum (1+7+3=11) = right sum (5+6=11).


How we deal with it

The idea is simple:

  1. First, calculate the total sum of the array.

  2. Keep a running leftSum = 0.

  3. For each index i:

    • Right sum = totalSum - leftSum - nums[i].

    • If leftSum == rightSum → that’s the pivot.

    • Else update leftSum += nums[i] and continue.

This way, we only pass the array once. Time complexity O(n), space O(1). Already optimal.


Code (Java)

class Solution {
    public int pivotIndex(int[] nums) {
        int total = 0, leftSum = 0;
        for (int num : nums) total += num;

        for (int i = 0; i < nums.length; i++) {
            if (leftSum == total - leftSum - nums[i]) {
                return i;
            }
            leftSum += nums[i];
        }
        return -1;
    }
}

Wrap-up

This problem is like a natural extension of the running sum logic we saw earlier. Instead of just building sums, now we are balancing them. ✨

See you in the next blog where we’ll continue with prefix-sum-based problems at a slightly higher level (like 560 and 523). 🚀