Skip to content

Commit d051955

Browse files
committed
Add Basic Prefix Sum Algorithm
1 parent 08d8c6b commit d051955

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

PrefixSum/BasicPrefixSum.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* BasicPrefixSum.js
3+
* Implementation of Prefix Sum array.
4+
*
5+
* @param {number[]} arr - Input array of numbers.
6+
* @returns {number[]} Prefix sum array.
7+
* @throws {TypeError} If input is not an array of numbers.
8+
*
9+
* Explanation:
10+
* Given [1,2,3,4], returns [1,3,6,10]
11+
*/
12+
13+
export function basicPrefixSum(arr) {
14+
// Validate input
15+
if (!Array.isArray(arr) || arr.some((x) => typeof x !== 'number')) {
16+
throw new TypeError('Input must be an array of numbers')
17+
}
18+
19+
// Handle empty array
20+
if (arr.length === 0) return []
21+
22+
const prefix = new Array(arr.length)
23+
prefix[0] = arr[0]
24+
25+
for (let i = 1; i < arr.length; i++) {
26+
prefix[i] = prefix[i - 1] + arr[i]
27+
}
28+
29+
return prefix
30+
}

PrefixSum/BasicPrefixSum.test.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { describe, it, expect } from 'vitest'
2+
import { basicPrefixSum } from './BasicPrefixSum.js'
3+
4+
describe('Basic Prefix Sum', () => {
5+
it('should compute prefix sum of a normal array', () => {
6+
const arr = [1, 2, 3, 4]
7+
const expected = [1, 3, 6, 10]
8+
expect(basicPrefixSum(arr)).toEqual(expected)
9+
})
10+
11+
it('should return empty array for empty input', () => {
12+
expect(basicPrefixSum([])).toEqual([])
13+
})
14+
15+
it('should throw TypeError for non-numeric array', () => {
16+
expect(() => basicPrefixSum([1, 'a', 3])).toThrow(TypeError)
17+
})
18+
19+
it('should handle single element array', () => {
20+
expect(basicPrefixSum([5])).toEqual([5])
21+
})
22+
23+
it('should handle negative numbers', () => {
24+
expect(basicPrefixSum([-1, -2, -3])).toEqual([-1, -3, -6])
25+
})
26+
})

0 commit comments

Comments
 (0)