Skip to content

Commit

Permalink
feat: prefix-sum-range added to leetcode problems along with test case
Browse files Browse the repository at this point in the history
  • Loading branch information
fauzulkc committed Aug 30, 2024
1 parent fdb8539 commit a228952
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
38 changes: 38 additions & 0 deletions apps/leet-code/src/problems/prefix-sum-range.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
export class NumArray
{
Inums: number[];
PrefixSum: number[] = [];
constructor ( nums: number[] )
{
this.Inums = [ ...nums ];
for ( let i = 0; i < nums.length; i++ ) {
if ( i === 0 ) {
this.PrefixSum[ i ] = nums[ i ];
} else {
this.PrefixSum[ i ] = nums[ i ] + nums[ i - 1 ];
}
}
}

sumRange ( left: number, right: number ): number
{
if ( left < 0 ) {
throw new Error( "Bad Starting Index Range" );
}

if ( right > this.Inums.length ) {
throw new Error( "Bad Ending Index Range" );
}
let sumRange = 0;
for ( let i = left; i <= right; i++ ) {
sumRange += this.PrefixSum[ i ];
}
return sumRange;
}
}

/**
* Your NumArray object will be instantiated and called as such:
* var obj = new NumArray(nums)
* var param_1 = obj.sumRange(left,right)
*/
11 changes: 11 additions & 0 deletions apps/leet-code/src/specs/prefix-sum-range.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { NumArray } from '../problems/prefix-sum-range';

describe( 'Sum of Cumulative Total in Range', () =>
{
it( 'should print 40 if the cumulative sum is checked from range from 1 to 4 in the array provided', () =>
{
expect( new NumArray( [ 1, 4, 5, 6, 9 ] ).sumRange( 1, 4 ) ).toBe(
40
);
} );
} );

0 comments on commit a228952

Please sign in to comment.