Java, O(n), sets, clean, 7 ms
This problem has two main cases - when k == 0 and all others. The idea is - for number n if there is n + k in the array - pair is possible. We add all numbers f
This problem has two main cases - when k == 0 and all others. The idea is - for number n if there is n + k in the array - pair is possible. We add all numbers from array to the set, then check for n + k. For k == 0 we need to count how many unqiue numbers repeated 2+ times. For that I use second set - add number that we met for the second time to that second set, then size of that second set will be the result.\n\nO(n) for time - 2 linear scans of the array. O(n) for space - need to store numbers to the set.\n\n```\n    public int findPairs(int[] nums, int k) {\n        if (k < 0)\n            return 0;\n        int res = 0;\n        Set<Integer> set = new HashSet();\n        //if k == 0 we need to count only repeated nums\n        //for that we need second set that indicats which num we have\n        //count already\n        if (k == 0 ) {\n            Set<Integer> seen = new HashSet();\n            for (int n : nums) {\n                //if we met this num before - add it to the second set\n                if (set.contains(n)) {\n                    seen.add(n);\n                } else\n                    set.add(n);\n            }\n            //size of second set will be the resulting num\n            res = seen.size();\n        } else {\n            //for k > 0 we check if n + k is in the set, this means we have a pair\n            for (int n : nums) {\n                set.add(n);\n            }\n\n            for (int n : set) {\n                if (set.contains(n + k))\n                    res++;\n            }\n        }\n        return res;\n    }\n```
['Java']