Create Sorted Array through Instructions LeetCode solution in JavaScript

1
var createSortedArray = function (instructions) {
2
let nums = [];
3
let cost = 0;
4
// define a map to track how many occurences of a number are in the array as we sort it
5
let map = {};
6
// classic binary search
7
const bin = (arr, elem) => {
8
let low = 0;
9
let high = arr.length - 1;
10
while (low <= high) {
11
let mid = (high + low) >> 1; // fancy Math.foor(high + low / 2)
12
if (arr[mid] > elem) {
13
high = mid - 1;
14
} else {
15
low = mid + 1;
16
}
17
}
18
return low;
19
};
20
// loop through the each of the values
21
for (let i of instructions) {
22
// do a binary search to determine which index this value belongs at
23
let index = bin(nums, i);
24
// insert it into the array
25
nums.splice(index, 0, i);
26
// populate a map to track how many instances of this number we have in the arr
27
if (!map.hasOwnProperty(i)) map[i] = 0;
28
// need to remove any matching numbers from the equation, meaning if the left side is 1,2,3,3
29
// and the current value is 3, we should be subtracting the existing 3's from the equation
30
let left = index - map[i];
31
// right side is the last value - index
32
let right = nums.length - 1 - index;
33
// add the min of left / right to the cost
34
cost += Math.min(left, right);
35
// increment our number occurence map
36
map[i]++;
37
}
38

39
const WEIRD_MOD_VAL = Math.pow(10, 9) + 7;
40
// for some goofy reason when the number is too large, send the mod val
41
return cost < 1842204555 ? cost : cost % WEIRD_MOD_VAL;
42
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0