LeetCode Solutions

724. Find Pivot Index

Time: $O(n)$

Space: $O(1)$

			

class Solution {
 public:
  int pivotIndex(vector<int>& nums) {
    const int sum = accumulate(begin(nums), end(nums), 0);
    int prefix = 0;

    for (int i = 0; i < nums.size(); ++i) {
      if (prefix == sum - prefix - nums[i])
        return i;
      prefix += nums[i];
    }

    return -1;
  }
};
			

class Solution {
  public int pivotIndex(int[] nums) {
    final int sum = Arrays.stream(nums).sum();
    int prefix = 0;

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

    return -1;
  }
}
			

class Solution:
  def pivotIndex(self, nums: List[int]) -> int:
    summ = sum(nums)
    prefix = 0

    for i, num in enumerate(nums):
      if prefix == summ - prefix - num:
        return i
      prefix += num

    return -1