Home Leetcode 724 - Find Pivot Index
Post
Cancel

Leetcode 724 - Find Pivot Index

Link to problem

Description

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.

Solution

We could use two prefix sum to solve this problem, with one starting from the end of the input nums. Then we could iterate the two prefix sum to check where the numbers meets and get the index. The time complexity of this algorithm would be $O(n)$ and space complexity also $O(n)$.

However, since we are comparing two prefix sum on the same index, we could get the prefix sum on the fly and only save the number we are currently processing, we can optimize the space complexity to be $O(1)$.

Implementation

  • Time complexity: $O(n)$, space complexity $O(n)$.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    class Solution {
    public:
      int pivotIndex(vector<int>& nums) {
          size_t n = nums.size();
          vector<int> prefix(n), suffix(n);
          prefix[0] = nums[0];
          suffix[n-1] = nums[n-1];
    
          for (int i = 1; i < n; i++) {
              prefix[i] = prefix[i-1] + nums[i];
              suffix[n-i-1] = suffix[n-i] + nums[n-i-1];
          }
    
          for (int i = 0; i < n; i++) {
              if (prefix[i] == suffix[i]) return i;
          }
    
          return -1;
      }
    };
    
  • Time complexity: $O(n)$, space complexity $O(1)$.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    class Solution {
    public:
      int pivotIndex(vector<int>& nums) {
          int prefix = 0;
          int suffix = reduce(nums.begin(), nums.end());
    
          for (int i = 0; i < nums.size(); i++) {
              prefix += nums[i];
              if (prefix == suffix) return i;
              suffix -= nums[i];
          }
    
          return -1;
      }
    };
    
This post is licensed under CC BY 4.0 by the author.