LeetCode - Find Pivot Index
Author: Qi Wang
Appears In
Time Complexity: .
Solution 1
The pivot index must have the same sum on its left and its right. To calculate this, we can create a prefix sum of the array (in my solution it is cushioned with one at index ). Loop through every index in the array and check whether
If this is true, we can return our current index because the problem wants the left-most index. If it finishes the for-loop without returning, it means there is no valid pivot index so return .
C++
Implementation
//Created by Qi Wangclass Solution {public:int pivotIndex(vector<int>& nums) {vector<int> psums{0};//Constructing psumsfor (int num : nums) psums.push_back(psums.back()+num);for(int i = 0; i<psums.size()-1; i++){
Java
Implementation
//Created by Qi Wangclass Solution {public int pivotIndex(int[] nums) {List<Integer> psums = new ArrayList<>();//Constructing psumspsums.add(0);for (int num : nums) psums.add(psums.get(psums.size()-1)+num);
Python
Implementation
# Created by Qi Wangclass Solution:def pivotIndex(self, nums: List[int]) -> int:psums = [0]for i in range(len(nums)):# Notice i in psums is always one less than the current indexpsums.append(psums[i] + nums[i]);for i in range(len(nums)):# Checking whether the left and the right are equal in areaif psums[i] == psums[len(nums)] - psums[i+1]:return i;return -1;
Solution 2
The alternate solution does not require an array to store the sums. Instead, we only need the total sum of the array and the current sum at each index (exclusive of index). With this we check whether
Note: This is technically the same solution as solution 1, but it is another way to think about approaching this question.
C++
Implementation
//Created by Qi Wangclass Solution {public:int pivotIndex(vector<int>& nums) {int total = 0;for(int x : nums)total += x;int curSum = 0;for(int i = 0; i<nums.size(); i++){
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!