Skip to content

Commit 62382f5

Browse files
committed
Hashing: Missing Number
1 parent 63b82fd commit 62382f5

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/hashing/missing-number.ts

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
export function missingNumber(nums: number[]): number {
2+
const n = nums.length;
3+
4+
/**
5+
* Partial sums
6+
* @see https://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF#Partial_sums
7+
*/
8+
const rangeSum = (n * (n + 1)) / 2;
9+
const numsSum = nums.reduce((total, num) => total + num, 0);
10+
11+
return rangeSum - numsSum;
12+
}

tests/hashing/missing-number.test.ts

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { missingNumber } from '@/hashing/missing-number.js';
2+
3+
describe('Hashing: Missing Number', () => {
4+
test.each([
5+
{
6+
nums: [3, 0, 1],
7+
output: 2,
8+
},
9+
{
10+
nums: [0, 1],
11+
output: 2,
12+
},
13+
{
14+
nums: [9, 6, 4, 2, 3, 5, 7, 0, 1],
15+
output: 8,
16+
},
17+
])('missingNumber($nums) === $output', ({ nums, output }) => {
18+
expect(missingNumber(nums)).toStrictEqual(output);
19+
});
20+
});

0 commit comments

Comments
 (0)