# Prefix Sum Array – Implementation and Applications in Competitive Programming

Given an array arr[] of size n, its prefix sum array is another array prefixSum[] of same size such that the value of prefixSum[i] is arr[0] + arr[1] + arr[2] … arr[i].

**Examples :**

Input : arr[] = {10, 20, 10, 5, 15} Output : prefixSum[] = {10, 30, 40, 45, 60} Explanation : While traversing the array, update the element by adding it with its previous element. prefixSum[0] = 10, prefixSum[1] = prefixSum[0] + arr[1] = 30, prefixSum[2] = prefixSum[1] + arr[2] = 40 and so on.

To fill prefix sum array, we run through index 1 to last and keep on adding present element with previous value in prefix sum array.

Below is the implementation :

## C++

`// C++ program for Implementing ` `// prefix sum array ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// Fills prefix sum array ` `void` `fillPrefixSum(` `int` `arr[], ` `int` `n, ` `int` `prefixSum[]) ` `{ ` ` ` `prefixSum[0] = arr[0]; ` ` ` ` ` `// Adding present element ` ` ` `// with previous element ` ` ` `for` `(` `int` `i = 1; i < n; i++) ` ` ` `prefixSum[i] = prefixSum[i-1] + arr[i]; ` `} ` ` ` `// Driver Code ` `int` `main() ` `{ ` ` ` `int` `arr[] = { 10, 4, 16, 20 }; ` ` ` `int` `n = ` `sizeof` `(arr) / ` `sizeof` `(arr[0]); ` ` ` `int` `prefixSum[n]; ` ` ` ` ` `fillPrefixSum(arr, n, prefixSum); ` ` ` `for` `(` `int` `i = 0; i < n; i++) ` ` ` `cout << prefixSum[i] << ` `" "` `; ` `} ` |

*chevron_right*

*filter_none*

## Java

`// Java Program for Implementing ` `// prefix sum arrayclass ` `class` `Prefix ` `{ ` ` ` `// Fills prefix sum array ` ` ` `static` `void` `fillPrefixSum(` `int` `arr[], ` `int` `n, ` ` ` `int` `prefixSum[]) ` ` ` `{ ` ` ` `prefixSum[` `0` `] = arr[` `0` `]; ` ` ` ` ` `// Adding present element ` ` ` `// with previous element ` ` ` `for` `( ` `int` `i = ` `1` `; i < n; ++i ) ` ` ` `prefixSum[i] = prefixSum[i-` `1` `] + arr[i]; ` ` ` `} ` ` ` ` ` `// Driver code ` ` ` `public` `static` `void` `main(String[] args) ` ` ` `{ ` ` ` `int` `arr[] = { ` `10` `, ` `4` `, ` `16` `, ` `20` `}; ` ` ` `int` `n = arr.length; ` ` ` `int` `prefixSum[] = ` `new` `int` `[n]; ` ` ` ` ` `fillPrefixSum(arr, n, prefixSum); ` ` ` ` ` `for` `(` `int` `i = ` `0` `; i < n; i++) ` ` ` `System.out.print(prefixSum[i] + ` `" "` `); ` ` ` `System.out.println(` `""` `); ` ` ` `} ` ` ` `} ` ` ` `// This Code is Contributed by Saket Kumar ` |

*chevron_right*

*filter_none*

## Python3

`# Python Program for Implementing ` `# prefix sum array ` ` ` `# Fills prefix sum array ` `def` `fillPrefixSum(arr, n, prefixSum): ` ` ` ` ` `prefixSum[` `0` `] ` `=` `arr[` `0` `] ` ` ` ` ` `# Adding present element ` ` ` `# with previous element ` ` ` `for` `i ` `in` `range` `(` `1` `, n): ` ` ` `prefixSum[i] ` `=` `prefixSum[i ` `-` `1` `] ` `+` `arr[i] ` ` ` `# Driver code ` `arr ` `=` `[` `10` `, ` `4` `, ` `16` `, ` `20` `] ` `n ` `=` `len` `(arr) ` ` ` `prefixSum ` `=` `[` `0` `for` `i ` `in` `range` `(n ` `+` `1` `)] ` ` ` `fillPrefixSum(arr, n, prefixSum) ` ` ` `for` `i ` `in` `range` `(n): ` ` ` `print` `(prefixSum[i] , ` `" "` `, end` `=` `"") ` ` ` `# This code is contributed ` `# by Anant Agarwal. ` |

*chevron_right*

*filter_none*

## C#

`// C# Program for Implementing ` `// prefix sum arrayclass ` `using` `System; ` ` ` `class` `GFG ` `{ ` ` ` `// Fills prefix sum array ` ` ` `static` `void` `fillPrefixSum(` `int` `[]arr, ` `int` `n, ` ` ` `int` `[]prefixSum) ` ` ` `{ ` ` ` `prefixSum[0] = arr[0]; ` ` ` ` ` `// Adding present element ` ` ` `// with previous element ` ` ` `for` `( ` `int` `i = 1; i < n; ++i ) ` ` ` `prefixSum[i] = prefixSum[i - 1] + arr[i]; ` ` ` `} ` ` ` ` ` `// Driver code ` ` ` `public` `static` `void` `Main() ` ` ` `{ ` ` ` `int` `[]arr = { 10, 4, 16, 20 }; ` ` ` `int` `n = arr.Length; ` ` ` `int` `[]prefixSum = ` `new` `int` `[n]; ` ` ` ` ` `fillPrefixSum(arr, n, prefixSum); ` ` ` ` ` `for` `(` `int` `i = 0; i < n; i++) ` ` ` `Console.Write(prefixSum[i] + ` `" "` `); ` ` ` `Console.Write(` `""` `); ` ` ` `} ` ` ` `} ` ` ` `// This Code is Contributed by nitin mittal ` |

*chevron_right*

*filter_none*

## PHP

`<?php ` `// PHP program for ` `// Implementing prefix ` `// sum array ` ` ` `// Fills prefix sum array ` `function` `fillPrefixSum(` `$arr` `, ` ` ` `$n` `) ` `{ ` ` ` `$prefixSum` `= ` `array` `(); ` ` ` `$prefixSum` `[0] = ` `$arr` `[0]; ` ` ` ` ` `// Adding present element ` ` ` `// with previous element ` ` ` `for` `(` `$i` `= 1; ` `$i` `< ` `$n` `; ` `$i` `++) ` ` ` `$prefixSum` `[` `$i` `] = ` `$prefixSum` `[` `$i` `- 1] + ` ` ` `$arr` `[` `$i` `]; ` ` ` ` ` `for` `(` `$i` `= 0; ` `$i` `< ` `$n` `; ` `$i` `++) ` ` ` `echo` `$prefixSum` `[` `$i` `] . ` `" "` `; ` `} ` ` ` `// Driver Code ` `$arr` `= ` `array` `(10, 4, 16, 20); ` `$n` `= ` `count` `(` `$arr` `); ` ` ` `fillPrefixSum(` `$arr` `, ` `$n` `); ` ` ` `// This code is contributed ` `// by Sam007 ` `?> ` |

*chevron_right*

*filter_none*

**Output:**

10 14 30 50

**Applications :**

- Equilibrium index of an array : Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes.
- Find if there is a subarray with 0 sum : Given an array of positive and negative numbers, find if there is a subarray (of size at-least one) with 0 sum.
- Maximum subarray size, such that all subarrays of that size have sum less than k : Given an array of n positive integers and a positive integer k, the task is to find the maximum subarray size such that all subarrays of that size have sum of elements less than k.
- Find the prime numbers which can written as sum of most consecutive primes : Given an array of limits. For every limit, find the prime number which can be written as the sum of the most consecutive primes smaller than or equal to limit.
- Longest Span with same Sum in two Binary arrays : Given two binary arrays arr1[] and arr2[] of same size n. Find length of the longest common span (i, j) where j >= i such that arr1[i] + arr1[i+1] + …. + arr1[j] = arr2[i] + arr2[i+1] + …. + arr2[j].
- Maximum subarray sum modulo m : Given an array of n elements and an integer m. The task is to find the maximum value of the sum of its subarray modulo m i.e find the sum of each subarray mod m and print the maximum value of this modulo operation.
- Maximum subarray size, such that all subarrays of that size have sum less than k : Given an array of n positive integers and a positive integer k, the task is to find the maximum subarray size such that all subarrays of that size have sum of elements less than k.
- Maximum occurred integer in n ranges : Given n ranges of the form L and R, the task is to find the maximum occurred integer in all the ranges. If more than one such integer exits, print the smallest one.
- Minimum cost for acquiring all coins with k extra coins allowed with every coin : You are given a list of N coins of different denominations. you can pay an amount equivalent to any 1 coin and can acquire that coin. In addition, once you have paid for a coin, we can choose at most K more coins and can acquire those for free. The task is to find the minimum amount required to acquire all the N coins for a given value of K.
- Random number generator in arbitrary probability distribution fashion : Given n numbers, each with some frequency of occurrence. Return a random number with probability proportional to its frequency of occurrence.

**An Example Problem : **

Consider an array of size n with all initial values as 0. Perform given ‘m’ add operations from index ‘a’ to ‘b’ and evaluate highest element in array. An add operation adds 100 to all elements from a to b (both inclusive).

Example :

Input : n = 5 // We consider array {0, 0, 0, 0, 0} m = 3. a = 2, b = 4. a = 1, b = 3. a = 1, b = 2. Output : 300 Explanation : After I operation - A : 0 100 100 100 0 After II operation - A : 100 200 200 100 0 After III operation - A : 200 300 200 100 0 Highest element : 300

A simple approach is running a loop ‘m’ times. Inputting a and b and running a loop from a to b, adding all elements by 100.

Efficient approach using **Prefix Sum Array** :

1 : Run a loop for 'm' times, inputting 'a' and 'b'. 2 : Add 100 at index 'a' and subtract 100 from index 'b+1'. 3 : After completion of 'm' operations, compute the prefix sum array. 4 : Scan the largest element and we're done.

What we did was adding 100 at ‘a’ because this will add 100 to all elements while taking prefix sum array. Subtracting 100 from ‘b+1’ will reverse the changes made by adding 100 to elements from ‘b’ onward.

For better understanding :

After I operation - A : 0 100 0 0 -100 Prefix Sum Array : 0 100 100 100 0 After II operation - A : 100 100 0 -100 -100 Prefix Sum Array : 100 200 200 100 0 After III operation - A : 200 100 -100 -100 -100 Prefix Sum Array : 200 300 200 100 0 Final Prefix Sum Array : 200 300 200 100 0 The required highest element : 300

Recent Articles on Prefix Sum Technique

This article is contributed by **Rohit Thapliyal**. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

## Recommended Posts:

- Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
- Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
- Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
- How can competitive programming help you get a job?
- How to become a master in competitive programming?
- Bit Tricks for Competitive Programming
- What is Competitive Programming and How to Prepare for It?
- What Are The Best Resources For Competitive Programming?
- How to begin with Competitive Programming?
- Python in Competitive Programming
- Fast I/O for Competitive Programming
- A Better Way To Approach Competitive Programming
- C++ tricks for competitive programming (for C++ 11)
- Some important shortcuts in Competitive Programming
- Bitwise Hacks for Competitive Programming