Skip to content

Commit 5e102f6

Browse files
authored
Add files via upload
1 parent 95492c5 commit 5e102f6

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

FindClosestElement.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
var findClosestElements = function (arr, k, x) {
2+
const res = [];
3+
let left = 0,
4+
right = arr.length - k;
5+
6+
// find lowest bound using binary search
7+
while (left < right) {
8+
const mid = Math.floor((left + right) / 2);
9+
const r_distance = arr[mid + k] - x;
10+
const l_distance = x - arr[mid];
11+
12+
// if arr[mid + k] closer to x -> search right half;
13+
//if arr[mid] closer to x -> search left half
14+
r_distance < l_distance ? (left = mid + 1) : (right = mid);
15+
}
16+
17+
for (let i = left; i < left + k; i++) res.push(arr[i]);
18+
19+
return res;
20+
};
21+
22+
console.log(findClosestElements([1, 2, 3, 4, 5], 4, 3));
23+
console.log(findClosestElements([1, 2, 3, 4, 5], 4, -1));

GenerateParenthesis.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
var generateParenthesis = function (n) {
2+
const arr = [];
3+
4+
const pairs = (string, open, close) => {
5+
if (string.length >= n * 2) arr.push(string);
6+
if (open < n) pairs(string + "(", open + 1, close);
7+
if (close < open) pairs(string + ")", open, close + 1);
8+
9+
return arr;
10+
};
11+
12+
return pairs("", 0, 0);
13+
};
14+
console.log(generateParenthesis(3));

0 commit comments

Comments
 (0)