Simple Solution with Diagrams in Video - JavaScript, C++, Java, Python
Video\nPlease upvote here so others save time too\n\nLike the video on YouTube if you found it useful\n\nClick here to subscribe on YouTube:\nhttps://www.youtub
# Video\nPlease upvote here so others save time too\n\nLike the video on YouTube if you found it useful\n\nClick here to subscribe on YouTube:\nhttps://www.youtube.com/@mayowadan?sub_confirmation=1\n\nThanks!\n\nhttps://youtu.be/weJC2lzSZAw?si=RtS9m-g-XQq4Dk51\n\n```Javascript []\nvar findClosestElements = function (nums, k, target) {\n    // If the length of \'nums\' is the same as k, return\n    // \'nums\'\n    if (nums.length === k) {\n        return nums;\n    }\n\n    // if target is less than or equal to first element in\n    // \'nums\', return the first k elements from \'nums\'\n    if (target <= nums[0]) {\n        return nums.slice(0, k);\n    }\n\n    // if target is greater than or equal to last element\n    // in \'nums\', return the last k elements from \'nums\'\n    if (target >= nums[nums.length - 1]) {\n        return nums.slice(nums.length - k);\n    }\n\n    // find the first closest element to target using\n    // binary search\n    const firstClosest = binarySearch(nums, target);\n\n    // initialize the sliding window pointers\n    let windowLeft = firstClosest - 1;\n    let windowRight = windowLeft + 1;\n\n    // expand the sliding window until its size becomes\n    // equal to k\n    while (windowRight - windowLeft - 1 < k) {\n        // if window\'s left pointer is going out of bounds\n        // move the window rightward\n        if (windowLeft === -1) {\n            windowRight++;\n            continue;\n        }\n\n        // if window\'s right pointer is going out of bounds\n        // OR if the element pointed to by window\'s left\n        // pointer is closer to target than the element\n        // pointed to by window\'s right pointer, move the\n        // window leftward\n        if (\n            windowRight === nums.length ||\n            Math.abs(nums[windowLeft] - target) <=\n            Math.abs(nums[windowRight] - target)\n        ) {\n            windowLeft--;\n        }\n        // if the element pointed to by window\'s right\n        // pointer is closer to target than the element\n        // pointed to by window\'s left pointer, move the\n        // window rightward\n        else {\n            windowRight++;\n        }\n    }\n\n    // return k closest elements present inside the window\n    return nums.slice(windowLeft + 1, windowRight);\n};\n\n\nfunction binarySearch(array, target) {\n    // initialize the left and the right pointer\n    let left = 0;\n    let right = array.length - 1;\n\n    // find the first closest element to target while\n    // left is less than or equal to right\n    while (left <= right) {\n        // compute the middle index\n        let mid = Math.floor((left + right) / 2);\n\n        // if the value at mid is equal to target,\n        // return mid\n        if (array[mid] === target) {\n            return mid;\n        }\n\n        // if the value at mid is less than target, move\n        // left forward\n        if (array[mid] < target) {\n            left = mid + 1;\n            // if the value at mid is greater than target,\n            // move right backward\n        } else {\n            right = mid - 1;\n        }\n    }\n    return left;\n}\n```\n```Python []\nfrom typing import List\n\n\nclass Solution:\n    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n        # If the length of \'arr\' is the same as k, return \'arr\'\n        if len(arr) == k:\n            return arr\n\n        # If target is less than or equal to the first element in \'arr\', return the first k elements\n        if x <= arr[0]:\n            return arr[:k]\n\n        # If target is greater than or equal to the last element in \'arr\', return the last k elements\n        if x >= arr[-1]:\n            return arr[-k:]\n\n        # Find the first closest element to target using binary search\n        firstClosest = self.binarySearch(arr, x)\n\n        # Initialize the sliding window pointers\n        windowLeft = firstClosest - 1\n        windowRight = windowLeft + 1\n\n        # Expand the sliding window until its size becomes equal to k\n        while windowRight - windowLeft - 1 < k:\n            # If window\'s left pointer is going out of bounds, move the window rightward\n            if windowLeft < 0:\n                windowRight += 1\n                continue\n\n            # If window\'s right pointer is going out of bounds OR if the element pointed to by window\'s left\n            # pointer is closer to target than the element pointed to by window\'s right pointer, move the\n            # window leftward\n            if windowRight == len(arr) or abs(arr[windowLeft] - x) <= abs(\n                arr[windowRight] - x\n            ):\n                windowLeft -= 1\n            # If the element pointed to by window\'s right pointer is closer to target than the element\n            # pointed to by window\'s left pointer, move the window rightward\n            else:\n                windowRight += 1\n\n        # Return k closest elements present inside the window\n        return arr[windowLeft + 1 : windowRight]\n\n    def binarySearch(self, array: List[int], target: int) -> int:\n        # Initialize the left and right pointers\n        left, right = 0, len(array) - 1\n\n        # Find the first closest element to target while left is less than or equal to right\n        while left <= right:\n            # Compute the middle index\n            mid = left + (right - left) // 2\n\n            # If the value at mid is equal to target, return mid\n            if array[mid] == target:\n                return mid\n\n            # If the value at mid is less than target, move left forward\n            if array[mid] < target:\n                left = mid + 1\n            # If the value at mid is greater than target, move right backward\n            else:\n                right = mid - 1\n\n        return left\n\n```\n```Java []\nimport java.util.ArrayList;\nimport java.util.List;\n\nclass Solution {\n    public List<Integer> findClosestElements(int[] arr, int k, int x) {\n        // If the length of \'arr\' is the same as k, return \'arr\'\n        if (arr.length == k) {\n            List<Integer> result = new ArrayList<>();\n            for (int num : arr) {\n                result.add(num);\n            }\n            return result;\n        }\n\n        // If target is less than or equal to the first element in \'arr\', return the\n        // first k elements\n        if (x <= arr[0]) {\n            List<Integer> result = new ArrayList<>();\n            for (int i = 0; i < k; i++) {\n                result.add(arr[i]);\n            }\n            return result;\n        }\n\n        // If target is greater than or equal to the last element in \'arr\', return the\n        // last k elements\n        if (x >= arr[arr.length - 1]) {\n            List<Integer> result = new ArrayList<>();\n            for (int i = arr.length - k; i < arr.length; i++) {\n                result.add(arr[i]);\n            }\n            return result;\n        }\n\n        // Find the first closest element to target using binary search\n        int firstClosest = binarySearch(arr, x);\n\n        // Initialize the sliding window pointers\n        int windowLeft = firstClosest - 1;\n        int windowRight = windowLeft + 1;\n\n        // Expand the sliding window until its size becomes equal to k\n        while (windowRight - windowLeft - 1 < k) {\n            // If window\'s left pointer is going out of bounds, move the window rightward\n            if (windowLeft < 0) {\n                windowRight++;\n                continue;\n            }\n\n            // If window\'s right pointer is going out of bounds OR if the element pointed to\n            // by window\'s left\n            // pointer is closer to target than the element pointed to by window\'s right\n            // pointer, move the\n            // window leftward\n            if (windowRight == arr.length ||\n                    Math.abs(arr[windowLeft] - x) <= Math.abs(arr[windowRight] - x)) {\n                windowLeft--;\n            }\n            // If the element pointed to by window\'s right pointer is closer to target than\n            // the element\n            // pointed to by window\'s left pointer, move the window rightward\n            else {\n                windowRight++;\n            }\n        }\n\n        // Return k closest elements present inside the window\n        List<Integer> result = new ArrayList<>();\n        for (int i = windowLeft + 1; i < windowRight; i++) {\n            result.add(arr[i]);\n        }\n        return result;\n    }\n\n    private int binarySearch(int[] array, int target) {\n        // Initialize the left and right pointers\n        int left = 0;\n        int right = array.length - 1;\n\n        // Find the first closest element to target while left is less than or equal to\n        // right\n        while (left <= right) {\n            // Compute the middle index\n            int mid = left + (right - left) / 2;\n\n            // If the value at mid is equal to target, return mid\n            if (array[mid] == target) {\n                return mid;\n            }\n\n            // If the value at mid is less than target, move left forward\n            if (array[mid] < target) {\n                left = mid + 1;\n            }\n            // If the value at mid is greater than target, move right backward\n            else {\n                right = mid - 1;\n            }\n        }\n        return left;\n    }\n}\n\n```\n```C++ []\n#include <algorithm>\n#include <cmath>\n#include <vector>\nusing namespace std;\n\nclass Solution {\npublic:\n    vector<int> findClosestElements(vector<int>& arr, int k, int x) {\n        // If the length of \'arr\' is the same as k, return \'arr\'\n        if (arr.size() == k) {\n            return arr;\n        }\n\n        // If target is less than or equal to the first element in \'arr\', return\n        // the first k elements\n        if (x <= arr[0]) {\n            return vector<int>(arr.begin(), arr.begin() + k);\n        }\n\n        // If target is greater than or equal to the last element in \'arr\',\n        // return the last k elements\n        if (x >= arr[arr.size() - 1]) {\n            return vector<int>(arr.end() - k, arr.end());\n        }\n\n        // Find the first closest element to target using binary search\n        int firstClosest = binarySearch(arr, x);\n\n        // Initialize the sliding window pointers\n        int windowLeft = firstClosest - 1;\n        int windowRight = windowLeft + 1;\n\n        // Expand the sliding window until its size becomes equal to k\n        while (windowRight - windowLeft - 1 < k) {\n            // If window\'s left pointer is going out of bounds, move the window\n            // rightward\n            if (windowLeft == -1) {\n                windowRight++;\n                continue;\n            }\n\n            // If window\'s right pointer is going out of bounds OR if the\n            // element pointed to by window\'s left pointer is closer to target\n            // than the element pointed to by window\'s right pointer, move the\n            // window leftward\n            if (windowRight == arr.size() ||\n                abs(arr[windowLeft] - x) <= abs(arr[windowRight] - x)) {\n                windowLeft--;\n            }\n            // If the element pointed to by window\'s right pointer is closer to\n            // target than the element pointed to by window\'s left pointer, move\n            // the window rightward\n            else {\n                windowRight++;\n            }\n        }\n\n        // Return k closest elements present inside the window\n        return vector<int>(arr.begin() + windowLeft + 1,\n                           arr.begin() + windowRight);\n    }\n\nprivate:\n    int binarySearch(vector<int>& array, int target) {\n        // Initialize the left and the right pointer\n        int left = 0;\n        int right = array.size() - 1;\n\n        // Find the first closest element to target while left is less than or\n        // equal to right\n        while (left <= right) {\n            // Compute the middle index\n            int mid = left + (right - left) / 2;\n\n            // If the value at mid is equal to target, return mid\n            if (array[mid] == target) {\n                return mid;\n            }\n\n            // If the value at mid is less than target, move left forward\n            if (array[mid] < target) {\n                left = mid + 1;\n            }\n            // If the value at mid is greater than target, move right backward\n            else {\n                right = mid - 1;\n            }\n        }\n        return left;\n    }\n};\n\n```\n\n\n
['Python', 'C++', 'Java', 'Python3', 'JavaScript']