Sunday, February 25, 2024

[LeetCode] Find Pivot Index

Problem: Given an array of integers nums, calculate the pivot index of this array.

The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.

If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.

Return the leftmost pivot index. If no such index exists, return -1.

Example:

Input: nums = [1,7,3,6,5,6]
Output: 3
Explanation:
The pivot index is 3.
Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
Right sum = nums[4] + nums[5] = 5 + 6 = 11
Input: nums = [1,2,3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.
Input: nums = [2,1,-1]
Output: 0
Explanation:
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums[1] + nums[2] = 1 + -1 = 0


Approach: The approach is simple. We will calculate total sum first. Once we have calculated it, we just need to see at every index 'i' if Sum(nums[0]...nums[i - 1]) is equal to total sum - nums[i] - Sum(nums[0]...nums[i - 1]). Why?

What is Sum(nums[0]...nums[i - 1])? It is the sum of all the elements to the left of the element at i.

What is total sum - nums[i] - Sum(nums[0]...nums[i - 1])? It is the sume of the all the elements to the right of the element at index i. How?

  • total_sum = Sum(nums[0]...nums[n - 1])
  • total_sum - nums[i] = Sum(nums[0]...nums[i -1]) + Sum(nums[i + 1]...nums[n - 1])
  • total_sum - nums[i] - Sum(nums[0]...nums[i - 1]) = Sum(nums[i + 1]...nums[n - 1])

We can clearly see Sum(nums[i + 1]...nums[n - 1]) is sum of all the elements to the right of the element at index 'i'.

That's all!


Implementation in C#:

    public int PivotIndex(int[] nums)
    {
        int length = nums?.Length ?? 0;
        if (length == 0)
        {
            return -1;
        }
        int totalSum = this.SumOfArray(nums);
        int leftSum = 0;
        for (int i = 0; i < length; ++i)
        {
            if (leftSum == totalSum - nums[i] - leftSum )
            {
                return i;
            }
            leftSum += nums[i];
        }
        return -1;
    }

    private int SumOfArray(int[] nums)
    {
        int sum = 0;
        for (int i = 0; i < nums.Length; ++i)
        {
            sum += nums[i];
        }
        return sum;
    }

Complexity: O(n)

No comments:

Post a Comment