From d4a695ee29524a540c4cb4b4f785b76ca39e1e5d Mon Sep 17 00:00:00 2001 From: Chetan Khilare Date: Sun, 12 Jan 2025 19:23:26 -0500 Subject: [PATCH] Completed Competitive Coding 3 --- KDiffPairs.java | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 KDiffPairs.java diff --git a/KDiffPairs.java b/KDiffPairs.java new file mode 100644 index 00000000..4ca30b0f --- /dev/null +++ b/KDiffPairs.java @@ -0,0 +1,36 @@ + +/** + * Time Complexity: O(n) + * Space Complexity: O(n) + * + */ + +import java.util.HashMap; +import java.util.Map; + +public class KDiffPairs { + public int findPairs(int[] nums, int k) { + if (nums == null || nums.length == 0) { + return 0; + } + Map map = new HashMap<>(); + int count = 0; + for (int num : nums) { + if (!map.containsKey(num)) { + map.put(num, 0); + } + map.put(num, map.get(num) + 1); + } + + for (Map.Entry entry : map.entrySet()) { + int key = entry.getKey(); + int value = entry.getValue(); + if (k == 0 && map.get(key) > 1) { + count++; + } else if (k > 0 && map.containsKey(key + k)) { + count++; + } + } + return count; + } +}