Skip to content

Commit 042670a

Browse files
committed
update: added k smallest elements problem
1 parent 6ced3ff commit 042670a

File tree

1 file changed

+21
-0
lines changed
  • src/_Problems_/k-smallest-elements-in-array

1 file changed

+21
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* Find 4 smallest elements in an array
3+
*/
4+
5+
const MinHeap = require('../../_DataStructures_/Heaps/MinHeap');
6+
7+
function findKSmallest(collection, k) {
8+
if (!collection || !Array.isArray(collection)) {
9+
throw new Error('Invalid / missing collection');
10+
}
11+
12+
// create a MinHeap using the collection
13+
const mh = new MinHeap(collection);
14+
const result = [];
15+
for (let i = 0; i < k; i += 1) {
16+
result.push(mh.getMin());
17+
}
18+
return result;
19+
}
20+
21+
module.exports = findKSmallest;

0 commit comments

Comments
 (0)