We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Algorithms
- Search
- Pairs
- Discussions
Pairs
Pairs
Sort by
recency
|
1265 Discussions
|
Please Login in order to post a comment
java public static int pairs(int k, List arr) { int count = 0; int start = 0; Collections.sort(arr); for(int i = 1; i < arr.size(); i++){ int diff = arr.get(i) - arr.get(start); if(diff > k) { start++; i--; } else if (diff == k) { count++; start++; } } return count; }
Java solution using Lambdas
}
Golang Time Complexity: O(n) Space Complexity: O(n)
First: populates a hash map with all elements from the input array arr for quick lookups.
Second: For each element x, it checks if x - k and x + k exist in the hash map. if exist, count
The current element x is then removed from the hash map to prevent counting the same pair twice (e.g., counting (3, 5) when x=3 and then again when x=5)
}
`