---
# System prepended metadata

title: Prefix Sum
tags: [Prefix Sum, Week_1]

---

###### tags: `Week_1`, `Prefix Sum`

# Prefix Sum

## [1480. Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array/)

harry:
```typescript=1
function runningSum(nums: number[]): number[] {
  return nums.reduce((res, e, i)=>{
      if(i === 0) { 
          res[0] = e;
      }
      else {
          res[i] = res[i-1] + e;
      }
      return res
  }, [0]);
};
```

beny:

```csharp=
public class Solution {
    public int[] RunningSum(int[] nums) {   
        int[] result = new int[nums.Length];
        int sum = 0;
        for(int i = 0; i < nums.Length; i++){
            sum += nums[i];
            result[i] = sum;            
        }       
        return result;              
    }
}
```

## [724. Find Pivot Index](https://leetcode.com/problems/find-pivot-index/)

harry:
```typescript=
function pivotIndex(nums: number[]): number {
    let sum = nums.reduce((res, e)=>res+=e, 0);
    let previousSum = 0;
    for(let i = 0;i<nums.length;i++){
        if(previousSum === sum - nums[i] - previousSum) {
            return i;
        } else {
            previousSum+=nums[i];
        }
    }
    return -1;
};
```

sam:
```python=
class Solution:
    def pivotIndex(self, nums: List[int]) -> int:

        sums = sum(nums)
        leftsum = 0
        
        for i, num in enumerate(nums):
            if leftsum == (sums - num - leftsum):
                return i
            leftsum += num
        
        return -1
```