75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

532. K-diff Pairs in an Array (Medium)

Brute force

Code

class Solution {
public:
    int findPairs(vector<int>& nums, int k)
    {
        int n = nums.size();
        set<int> st;
        int a = 0, b = 0;
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                if (abs(nums[i] - nums[j]) == k) {
                    st.insert(min(nums[i], nums[j]));
                }
            }
        }
        return st.size();
    }
};

Code

class Solution {
public:
    int findPairs(vector<int>& nums, int k)
    {
        int n = nums.size();
        set<int> st;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < n - 1; i++) {
            if (binary_search(nums.begin() + i + 1, nums.end(), nums[i] + k)) {
                st.insert(nums[i]);
            }
        }
        return st.size();
    }
};

with hashmap

Code

class Solution {
public:
    int findPairs(vector<int>& nums, int k)
    {
        map<int, int> mp;
        for (auto x : nums)
            mp[x]++;

        int res = 0;
        for (auto x : mp) {
            if (k > 0 && mp.count(x.first + k) || k == 0 && x.second > 1)
                res++;
        }
        return res;
    }
};