Skip to content

Commit

Permalink
feat: add subarray with given sum
Browse files Browse the repository at this point in the history
  • Loading branch information
behzadam committed Jul 22, 2024
1 parent 9dbbbc4 commit 970dbc9
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/array/subarray-with-given-sum/subarray-with-given-sum.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { subarrayWithGivenSum } from "./subarray-with-given-sum";

describe("subarrayWithGivenSum", () => {
it.each([
{ arr: [], target: 5, expected: [] },
{ arr: [5], target: 5, expected: [0] },
{ arr: [2, 3], target: 5, expected: [0, 1] },
{ arr: [2, 3], target: 6, expected: [] },
{ arr: [1, 2, 3, 7, 5], target: 12, expected: [1, 3] },
{ arr: [1, 4, 20, 3, 10, 5], target: 33, expected: [2, 4] },
])(
"returns $expected for arr = $arr and target = $target",
({ arr, target, expected }) => {
expect(subarrayWithGivenSum(arr, target)).toEqual(expected);
}
);
});
44 changes: 44 additions & 0 deletions src/array/subarray-with-given-sum/subarray-with-given-sum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* Finds a subarray of a given array that sums up to a given target and returns its indices.
* @param arr - the array of numbers
* @param target - the target sum
*/
export function subarrayWithGivenSum(arr: number[], target: number): number[] {
// If the array is empty, return an empty array.
if (arr.length === 0) {
return [];
}

// If the array has only one element, check if it is equal to the target.
if (arr.length === 1) {
return arr[0] === target ? [0] : [];
}

// If the array has two elements, check if either of them is equal to the target or if their sum is equal to the target.
if (arr.length === 2) {
if (arr[0] === target || arr[1] === target) {
return [arr[0] === target ? 0 : 1];
} else if (arr[0] + arr[1] === target) {
return [0, 1];
} else {
return [];
}
}

let start = 0;
let end = 0;
let sum = arr[0];

while (end < arr.length) {
if (sum === target) {
return [start, end];
} else if (sum < target) {
end++;
sum += arr[end];
} else {
sum -= arr[start];
start++;
}
}
return [];
}

0 comments on commit 970dbc9

Please sign in to comment.