JavaScript - Two Pointers Approach Explained and Heavily Commented
I\'ll be happy if you can upvote <3\n\nThe approach is tow pointers, we loop while the subtraction of the right pointer from the left pointer is equal or higher
I\'ll be happy if you can upvote <3\n\nThe approach is tow pointers, we loop while the subtraction of the right pointer from the left pointer is equal or higher than k, because we want in the end k elements in the array.\nThen we perform the checking as described in the description of the question (just a simple calculation and an if statement).\nIf integer a (calcLeft) is closer to x, we decrement from the right pointer, because we want to save the left element.\nElse, if b (calcRight) is closer to x, we increment from the left pointer, because we want to save the right element.\nIn the end, we slice the array according to the pointers indices.\n\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    // We set our two pointers, one in the start of the array and the second one in the end.\n    let left = 0;\n    let right = arr.length - 1;\n    \n    // Because we need an array in size of k, we will run while the subtraction of the pointers is bigger or equal to k.\n    while(right - left >= k) {\n        \n        // We will calculate the left element (a) and the right element (b).\n        const calcLeft = Math.abs(arr[left] - x);\n        const calcRight = Math.abs(arr[right] - x);\n        \n        // We will do the checking according to the description.\n        // If a is closer to x, we decrement from the right pointer, else we will increment the left pointer because it means that the right element is closer to x.\n        if(calcLeft < calcRight || (calcLeft === calcRight && arr[left] < arr[right])) {\n            right--;\n        } else {\n            left++;\n        }\n    }  \n    \n    // We return the original arr sliced with the elements that are the closest to k.\n    return arr.slice(left, right + 1);\n};\n```
['Two Pointers', 'JavaScript']