C++✅ || Heap Logic🔥 || Simple & Fast Code 🚀 || Must See 📌
Intuition 🌟The goal is to find the k elements closest to x in the array. The difference between an element and x determines how close it is. By maintaining a ma
# Intuition 🌟  
The goal is to find the `k` elements closest to `x` in the array. The difference between an element and `x` determines how close it is. By maintaining a max heap of size `k`, we can efficiently keep track of the `k` closest elements.

# Approach 🚀  
1️⃣ Use a **max heap** to store pairs of the form `(diff, element)` where:  
   - `diff` is the absolute difference between the element and `x`.  
   - The heap is ordered by `diff`.  
2️⃣ Iterate through the array:  
   - For each element, compute its difference from `x`.  
   - Push the `(diff, element)` pair into the max heap.  
   - If the heap size exceeds `k`, pop the top element (farthest from `x`).  
3️⃣ Extract all elements from the heap into a result vector.  
4️⃣ Sort the result vector to ensure the elements are in ascending order.  

# Complexity 📊  
- **Time complexity**:  
   - Heap operations (push + pop) take $$O(\log{k})$$, and for `n` elements, it will take $$O(n \log{k})$$.  
   - Sorting the result vector takes $$O(k \log{k})$$.  
   Overall: $$O(n \log{k})$$  
- **Space complexity**:  
   - The heap takes $$O(k)$$ space.  
   Overall: $$O(k)$$  

# Code 💻  
```cpp []
class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        priority_queue<pair<int, int>> maxHeap; // Max heap to store {diff, element}
        
        for (int i = 0; i < arr.size(); i++) {
            int diff = abs(arr[i] - x); // Calculate absolute difference
            maxHeap.push({diff, arr[i]}); // Push {difference, element} into the heap
            
            if (maxHeap.size() > k) {
                maxHeap.pop(); // Remove the farthest element if heap size exceeds k
            }
        }
        
        vector<int> ans;
        while (!maxHeap.empty()) {
            ans.push_back(maxHeap.top().second); // Collect the elements from the heap
            maxHeap.pop();
        }
        
        sort(ans.begin(), ans.end()); // Sort the result in ascending order
        return ans;
    }
};
```
![upvote.jpeg](https://assets.leetcode.com/users/images/eb5fe101-6c73-4a7d-b3fc-dbc71c9091c1_1737902110.2937477.jpeg)

['Sorting', 'Heap (Priority Queue)', 'C++']