✅ Beats 99.99% || Two Pointer || K-diff Pairs in an Array
Intuition\nThe code aims to find the number of unique pairs (i, j) in the given vector nums such that the absolute difference between nums[i] and nums[j] is equ
# Intuition\nThe code aims to find the number of unique pairs (i, j) in the given vector nums such that the absolute difference between nums[i] and nums[j] is equal to the given integer k.\n\n# Approach\nSort the array nums to make it easier to find pairs with the desired difference.\nUse two pointers (i and j) to traverse the array.\nCalculate the absolute difference diff between nums[i] and nums[j].\nAdjust the pointers based on the value of diff:\nIf diff equals k, insert the pair (nums[i], nums[j]) into a set.\nIf diff is greater than k, move i to the next element.\nIf diff is less than k, move j to the next element.\nAvoid cases where i and j point to the same element.\nReturn the size of the set, which contains unique pairs.\n# Code Explanation:\nThe array nums is sorted to make it easier to find pairs with the desired difference.\nTwo pointers (i and j) are used to traverse the array and find pairs.\nThe set ans is used to store unique pairs with the desired difference.\nThe while loop continues until j reaches the end of the array.\nThe pointers are adjusted based on the absolute difference between nums[i] and nums[j].\nPairs satisfying the condition are added to the set.\nThe final result is the size of the set, indicating the number of unique pairs.\n\n# Complexity\nTime Complexity: O(n log n) - Sorting the array takes O(n log n) time, and the subsequent traversal takes O(n) time.\nSpace Complexity: O(n) - The set (ans) stores unique pairs, and in the worst case, it could store all pairs.\n\n# Code\n```\nclass Solution {\npublic:\n    int findPairs(vector<int>& nums, int k) {\n        sort(nums.begin(),nums.end());\n        set<pair<int,int>> ans;\n\n        int i = 0,j=1;\n        while(j<nums.size()){\n            int diff = nums[j]-nums[i];\n            if(diff == k){\n                ans.insert({nums[i],nums[j]});\n                ++i;\n                ++j;\n            }\n            else if(diff > k ){\n                i++;\n            }\n            else{\n                j++;\n            }\n            if(i == j){\n                j++;\n            }\n        }\n        return ans.size();\n    }\n};\n```
['Two Pointers', 'Binary Search', 'Sorting', 'C++']