JavaScript, Binary Search O(log N) / Stack O(N - K)
Two Pointer with Stack\n- Time Complexity: O(N - K) \n- Space Complexity: O(1)\n\nDuring the length of arr exceeds k, It will remove element which has bigger di
## Two Pointer with Stack\n- Time Complexity: O(N - K) \n- Space Complexity: O(1)\n\nDuring the length of `arr` exceeds `k`, It will remove element which has bigger difference with `x` from front and end of array iteratively. (If it have the same differences, remove a element from end)\n```JavaScript\n/**\n * @param {number[]} arr\n * @param {number} k\n * @param {number} x\n * @return {number[]}\n */\nvar findClosestElements = function(arr, k, x) {\n    let idx = 0;\n    while (k < arr.length - idx) {\n        const last = arr.pop();\n        if (last - x < x - arr[idx]) {\n            idx++;\n            arr.push(last);\n        }\n    }\n    return arr.slice(idx);\n};\n```\n\n## Binary Search\n- Time Complexity: O(log N)\n- Space Complexity: O(1)\n\n```JavaScript\n/**\n * @param {number[]} arr\n * @param {number} k\n * @param {number} x\n * @return {number[]}\n */\nvar findClosestElements = function(arr, k, x) {\n    let lo = 0, hi = arr.length - 1;\n    while (lo < hi) {\n        const mid = parseInt((lo + hi) / 2);\n        x - arr[mid] > arr[mid + k]- x ? lo = mid + 1 : hi = mid;\n    }\n    return arr.slice(lo, lo + k);\n};\n```\nIt will find the start index of result with binary search,\n\n- `x = 0` `k=3`\n- `x - arr[mid] > arr[mid + k] - x ? lo = mid + 1 : hi = mid;`\n\nval|-3|-2|-1|0|1|2|\n:--:|:--:|:--:|:--:|:--:|:--:|:--:\nidx|0|1|2|3|4|5|\npointer|lo||mid|||mid+k = hi\ny|||x - val = **1**|||val - x = **2**\npointer|lo||hi|||\n\nval|-3|-2|-1|0|1|2|\n:--:|:--:|:--:|:--:|:--:|:--:|:--:\nidx|0|1|2|3|4|5|\npointer|lo|mid|hi||mid + k|\ny||x-val=**2**|||val-x = **1**\n**break**|||lo=hi|||lo+k\n\n\n- `x = 1` `k=3`\n- `x - arr[mid] > arr[mid + k] - x ? lo = mid + 1 : hi = mid;`\n\nval|-3|-2|-1|0|1|2|\n:--:|:--:|:--:|:--:|:--:|:--:|:--:\nidx|0|1|2|3|4|5|\npointer|lo||mid|||mid+k = hi\ny|||x - val = **2**|||val - x = **1**\npointer||||lo||hi\n\n- `mid + k` exceeds array\'s length all the comparision return `false`\n\nval|-3|-2|-1|0|1|2|\n:--:|:--:|:--:|:--:|:--:|:--:|:--:\nidx|0|1|2|3|4|5|\npointer||||lo|mid|**hi**\npointer||||lo=mid|**hi**|\n**break**||||lo=**hi**||||\n\n- `x = -1` `k=3`\n- `x - arr[mid] > arr[mid + k] - x ? lo = mid + 1 : hi = mid;`\n\nval|-3|-2|-1|0|1|2|\n:--:|:--:|:--:|:--:|:--:|:--:|:--:\nidx|0|1|2|3|4|5|\npointer|lo||mid|||mid+k = hi\ny||| x-val = **0**|||val-x =**1**\npointer|lo||hi\n\nval|-3|-2|-1|0|1|2|\n:--:|:--:|:--:|:--:|:--:|:--:|:--:\nidx|0|1|2|3|4|5|\npointer|lo|mid|hi||mid+k\ny||x-val = **1**|||val-x = **2**\npointer|lo|hi\n\nval|-3|-2|-1|0|1|2|\n:--:|:--:|:--:|:--:|:--:|:--:|:--:\nidx|0|1|2|3|4|5|\npointer|lo=mid|hi||mid+k\ny|x-val = **2**|||val-x = **-1**\n**break**||lo=hi\n\n
['Stack', 'Binary Tree', 'JavaScript']