1
var createSortedArray = function (instructions) {4
// define a map to track how many occurences of a number are in the array as we sort it6
// classic binary search7
const bin = (arr, elem) => {9
let high = arr.length - 1;11
let mid = (high + low) >> 1; // fancy Math.foor(high + low / 2)12
if (arr[mid] > elem) {20
// loop through the each of the values21
for (let i of instructions) {22
// do a binary search to determine which index this value belongs at23
let index = bin(nums, i);24
// insert it into the array25
nums.splice(index, 0, i);26
// populate a map to track how many instances of this number we have in the arr27
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,329
// and the current value is 3, we should be subtracting the existing 3's from the equation30
let left = index - map[i];31
// right side is the last value - index32
let right = nums.length - 1 - index;33
// add the min of left / right to the cost34
cost += Math.min(left, right);35
// increment our number occurence map39
const WEIRD_MOD_VAL = Math.pow(10, 9) + 7;40
// for some goofy reason when the number is too large, send the mod val41
return cost < 1842204555 ? cost : cost % WEIRD_MOD_VAL;