JS / TS Solutions with Explanation Comments - Binary Search
Approach\nWe can solve this problem efficiently with binary search. \n\n# Complexity\n- Time complexity: O(logN)\n\nBinary search reduces the search range by ha
# Approach\nWe can solve this problem efficiently with binary search. \n\n# Complexity\n- Time complexity: **O(logN)**\n\nBinary search reduces the search range by half in each step, leading to logarithmic time complexity.\n\n- Space complexity **O(N)**:\n\nThe algorithm uses a constant amount of extra space for the pointers and variables, resulting in a space complexity that grows logarithmically with the input size.\n\n# Code - JavaScript\n```\n/**\n * @param {number[]} arr\n * @param {number} k\n * @param {number} x\n * @return {number[]}\n */\nvar findClosestElements = function(arr, k, x) {\n\n    // Let\'s use an example array [1, 2, 3, 4, 5] with k = 3 to explain the solution.\n\n    let left = 0;\n\n    // The right variable represents the maximum possible lower boundary.\n    // In this case, right becomes 5 - 3, which is 2.\n    // This means our search domain is from index 0 to index 2, allowing for possible values\n    // like [1, 2, 3], [2, 3, 4], and [3, 4, 5].\n\n    let right = arr.length - k;\n\n    while(left < right){\n\n        // Our binary search focuses only on the range from index 0 to 2.\n        // So the possible mid values are 0 and 1, as 2 is excluded due to the loop condition.\n\n        let mid = (left + right) >> 1;\n\n        // The condition involving arr[mid + k] is interesting.\n        // It\'s important to note that arr[mid + k] cannot exceed the array\'s length. Even if $mid is at its maximum,\n        // the result will be 1 + 3, which is 4, the index of the last item in the array.\n        // The condition seems reversed because it deals with absolute values,\n        // ensuring that the number less than the target is closer than a number greater than the target.\n\n        if(arr[mid] - x < x - arr[mid + k]){\n            left = mid + 1;\n        }else{\n            right = mid;\n        }\n    }\n\n    // We return the slice of the array that starts at the \'left\' index and extends for \'k\' elements.\n    return arr.slice(left, left + k);\n};\n```\n\n# Code - TypeScript\n```\nfunction findClosestElements(arr: number[], k: number, x: number): number[] {\n    let left = 0;\n    let right = arr.length - k;\n\n    while(left < right){\n        let mid = (left + right) >> 1;\n\n        if(arr[mid] - x < x - arr[mid + k]){\n            left = mid + 1;\n        }else{\n            right = mid;\n        }\n    }\n\n    return arr.slice(left, left + k);\n};\n\n```\n# Upvote\n\nPlease **upvote** if you find helpful.
['Binary Search', 'TypeScript', 'JavaScript']