Let's make this one less mysterious. For 724. Find Pivot Index, the solution in this repository is mainly a prefix sums solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: prefix sums.
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are pivotIndex.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(N)O(N), where NN is the length of nums.
- Space: O(1)O(1), the space used by leftsum and S.
Guide
C++ Solution
Your submission
The accepted solution
01/**
02Approach #1: Prefix Sum [Accepted]
03**/
04
05/**
06Complexity Analysis
07
08Time Complexity: O(N)O(N), where NN is the length of nums.
09
10Space Complexity: O(1)O(1), the space used by leftsum and S.
11**/
12
13//Runtime: 28 ms, faster than 98.42% of C++ online submissions for Find Pivot Index.
14//Memory Usage: 9.8 MB, less than 100.00% of C++ online submissions for Find Pivot Index.
15
16class Solution {
17public:
18 int pivotIndex(vector<int>& nums) {
19 int allsum = accumulate(nums.begin(), nums.end(), 0);
20 int cumsum = 0;
21
22 for(int i = 0; i < nums.size(); i++){
23 if(cumsum*2 == (allsum-nums[i])){
24 return i;
25 }
26 cumsum += nums[i];
27 }
28
29 return -1;
30 }
31};
Cost