KatInterview

724. Find Pivot Index

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find a "pivot index" in an array of integers. A pivot index is defined as an index where the sum of all numbers strictly to its left is equal to the sum of all numbers strictly to its right. We are required to find the leftmost such index. If no such index exists, we should return -1.

Solution

Find Pivot Index in Python

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        # Calculate the total sum of the array.
        total_sum = sum(nums)
        
        left_sum = 0
        
        # Iterate through the array with index and value.
        for i, num in enumerate(nums):
            # The right sum is total_sum - left_sum - current_num.
            # The condition for a pivot is left_sum == right_sum.
            # This can be rewritten by substituting right_sum:
            # left_sum == total_sum - left_sum - num
            # 2 * left_sum == total_sum - num
            if 2 * left_sum == total_sum - num:
                return i
            
            # Update left_sum for the next iteration.
            left_sum += num
            
        # If no pivot index is found after iterating through the whole array, return -1.
        return -1

Find Pivot Index in Java

class Solution {
    public int pivotIndex(int[] nums) {
        // Calculate the total sum of the array.
        long totalSum = 0;
        for (int num : nums) {
            totalSum += num;
        }

        long leftSum = 0;

        // Iterate through the array to find the pivot index.
        for (int i = 0; i < nums.length; i++) {
            // The condition for a pivot index is:
            // leftSum == rightSum
            // where rightSum = totalSum - leftSum - nums[i]
            // So, leftSum == totalSum - leftSum - nums[i]
            // which simplifies to 2 * leftSum == totalSum - nums[i]
            if (2 * leftSum == totalSum - nums[i]) {
                return i; // Found the pivot index.
            }

            // Update leftSum for the next iteration by adding the current element.
            leftSum += nums[i];
        }

        // If the loop completes without finding a pivot index, return -1.
        return -1;
    }
}

Find Pivot Index in C++

class Solution {
public:
    int pivotIndex(vector<int>& nums) {
        long long totalSum = 0;
        for (int num : nums) {
            totalSum += num;
        }
        
        long long leftSum = 0;
        
        // Iterate through the array to find the pivot index.
        for (int i = 0; i < nums.size(); ++i) {
            // The right sum can be calculated as totalSum - leftSum - nums[i].
            // The condition is leftSum == rightSum.
            // which is leftSum == totalSum - leftSum - nums[i].
            // This simplifies to 2 * leftSum == totalSum - nums[i].
            if (2 * leftSum == totalSum - nums[i]) {
                return i; // Found the pivot index.
            }
            
            // Update leftSum for the next iteration.
            leftSum += nums[i];
        }
        
        // If no pivot index is found after checking all elements, return -1.
        return -1;
    }
};

Find Pivot Index in TypeScript

function pivotIndex(nums: number[]): number {
    // Calculate the total sum of the array using reduce.
    const totalSum = nums.reduce((acc, curr) => acc + curr, 0);

    let leftSum = 0;

    // Iterate through the array to find the pivot index.
    for (let i = 0; i < nums.length; i++) {
        // The condition for a pivot index is:
        // leftSum === rightSum
        // where rightSum = totalSum - leftSum - nums[i]
        // This simplifies to: 2 * leftSum === totalSum - nums[i]
        if (2 * leftSum === totalSum - nums[i]) {
            return i; // Found the pivot index.
        }

        // Update leftSum for the next iteration.
        leftSum += nums[i];
    }

    // If the loop completes, no pivot index exists.
    return -1;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.