Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implemented prefix sum generation for given array #38

Merged
merged 1 commit into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions Array_Functions/Prefix_Sum/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Prefix Sum Algorithm

## Overview
The Prefix Sum algorithm computes the cumulative sum of elements in an array or list. This cumulative sum is also known as the "partial sum". It is often used in problems where you need to quickly calculate the sum of elements in a range or subarray.

## Example:
Given an array:

arr = [1, 2, 3, 4, 5]

The Prefix Sum array will store the cumulative sums up to each index:

prefix_sum = [0, 1, 3, 6, 10, 15]

Where:
- prefix_sum[0] = 0 (Initial value for easy range sum calculations)
- prefix_sum[i] = arr[0] + arr[1] + ... + arr[i-1]

## Visual Breakdown:

1. **Input Array:**

arr = [1, 2, 3, 4, 5]

2. **Prefix Sum Calculation:**
- prefix_sum[0] = 0 (initialized to 0)
- prefix_sum[1] = prefix_sum[0] + arr[0] = 0 + 1 = 1
- prefix_sum[2] = prefix_sum[1] + arr[1] = 1 + 2 = 3
- prefix_sum[3] = prefix_sum[2] + arr[2] = 3 + 3 = 6
- prefix_sum[4] = prefix_sum[3] + arr[3] = 6 + 4 = 10
- prefix_sum[5] = prefix_sum[4] + arr[4] = 10 + 5 = 15

3. **Resulting Prefix Sum Array:**

prefix_sum = [0, 1, 3, 6, 10, 15]
39 changes: 39 additions & 0 deletions Array_Functions/Prefix_Sum/prefix_sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#include <bits/stdc++.h>

using namespace std;

template <typename Iterator>
vector<int> generatePrefixSum(Iterator start, Iterator end) {
vector<int> prefixSum = {0};
int currentSum = 0;
for (Iterator it = start; it != end; ++it) {
currentSum += *it;
prefixSum.push_back(currentSum);
}
return prefixSum;
}

int main() {
//example with array
int a[] = {1, 2, 3, 4, 5};
int n = sizeof(a) / sizeof(a[0]);
vector<int> prefixSum = generatePrefixSum(a, a+n);

cout << "Prefix Sum for range: ";
for (int sum : prefixSum) {
cout << sum << " ";
}
cout << endl;

//example with vector
vector<int> b = {1, 2, 3, 4, 5};

vector<int> prefixSum2 = generatePrefixSum(b.begin(), b.end());

cout << "Prefix Sum for range: ";
for (int sum : prefixSum2) {
cout << sum << " ";
}
cout << endl;
return 0;
}
75 changes: 75 additions & 0 deletions Array_Functions/Prefix_Sum/prefix_sum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package CodeStock.Array_Functions.Prefix_Sum;

import java.util.*;

public class prefix_sum {

public static List<Integer> generatePrefixSum(int[] array, int start, int end) {
if (start < 1 || end > array.length || start > end) {
System.out.println("Invalid range for array. Please check the start and end indices.");
return Collections.emptyList();
}

List<Integer> prefixSum = new ArrayList<>();
prefixSum.add(0);

int currentSum = 0;

for (int i = start; i <= end; i++) {
currentSum += array[i - 1];
prefixSum.add(currentSum);
}

return prefixSum;
}

public static List<Integer> generatePrefixSum(List<Integer> list, int start, int end) {
if (start < 1 || end > list.size() || start > end) {
System.out.println("Invalid range for list. Please check the start and end indices.");
return Collections.emptyList();
}

List<Integer> prefixSum = new ArrayList<>();
prefixSum.add(0);

int currentSum = 0;

for (int i = start; i <= end; i++) {
currentSum += list.get(i - 1);
prefixSum.add(currentSum);
}

return prefixSum;
}

public static void main(String[] args) {
//example as array
int[] a = {1, 2, 3, 4, 5};
int startIndex = 1;
int endIndex = 4;

List<Integer> prefixSumArray = generatePrefixSum(a, startIndex, endIndex);

if (!prefixSumArray.isEmpty()) {
System.out.print("Prefix Sum for array subrange: ");
for (int sum : prefixSumArray) {
System.out.print(sum + " ");
}
System.out.println();
}
//example as list
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
startIndex = 1;
endIndex = 4;

List<Integer> prefixSumList = generatePrefixSum(list, startIndex, endIndex);

if (!prefixSumList.isEmpty()) {
System.out.print("Prefix Sum for list subrange: ");
for (int sum : prefixSumList) {
System.out.print(sum + " ");
}
System.out.println();
}
}
}
24 changes: 24 additions & 0 deletions Array_Functions/Prefix_Sum/prefix_sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
def generate_prefix_sum(iterable, start, end):
if start < 1 or end > len(iterable) or start > end:
print("Invalid range. Please ensure the range is within bounds and start <= end.")
return []

prefix_sum = [0]
current_sum = 0
for i in range(start - 1, end): # Adjusting for 1-based indexing
current_sum += iterable[i]
prefix_sum.append(current_sum)

return prefix_sum

if __name__ == "__main__":
# Example with a list
a = [1, 2, 3, 4, 5]
start_index = 2
end_index = 4

prefix_sum_a = generate_prefix_sum(a, start_index, end_index)
if prefix_sum_a: # Check if the range is valid and prefix sum is not empty
print("Prefix Sum for range (array):", " ".join(map(str, prefix_sum_a)))