658: Solution with step by step explanation
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Initialize two pointers "left" and "right" to point to the beginning a
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize two pointers "left" and "right" to point to the beginning and end of the array respectively.\n2. While the difference between "right" and "left" is greater than or equal to "k":\na. If the absolute difference between "x" and the element at "left" is greater than or equal to the absolute difference\nbetween "x" and the element at "right":\ni. Increment "left".\nb. Else, decrement "right".\n3. Return a sorted subarray of "arr" containing the elements between "left" and "right" (inclusive).\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n        left = 0\n        right = len(arr) - 1\n        \n        while right - left >= k:\n            if abs(x - arr[left]) > abs(x - arr[right]):\n                left += 1\n            else:\n                right -= 1\n        \n        return sorted(arr[left:right+1])\n\n```
['Two Pointers', 'Binary Search', 'Sliding Window', 'Python', 'Python3']