Leetcode 2006. Count Number of Pairs With Absolute Difference K
Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.
The absolute difference of two integers a and b is the absolute value of a - b.
1 <= nums.length <= 2001 <= nums[i] <= 1001 <= k <= 99Q: Should we consider only unique pairs?
A: Yes, each pair (i, j) should satisfy i < j.
Q: Can k be zero?
A: No, based on the constraints 1 <= k <= 99, k cannot be zero.
Q: Are duplicates allowed in the input array nums?
A: Yes, the array can have duplicate values.
The problem requires us to count pairs where the absolute difference between elements is exactly k. We can solve this problem using a brute force approach by checking all possible pairs and counting those satisfying the condition. Given the constraints, this approach will be efficient enough.
(i, j) in the array where i < j.|nums[i] - nums[j]| == k.count = 0
for i from 0 to len(nums) - 1
for j from i + 1 to len(nums)
if |nums[i] - nums[j]| == k
increment count
return count
The time complexity of this approach is O(n^2) where n is the number of elements in the array nums. This is because we are checking all possible pairs which involves a nested loop.
#include <vector>
#include <cstdlib> // for abs function
int countKDifference(std::vector<int>& nums, int k) {
int count = 0;
int n = nums.size();
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (std::abs(nums[i] - nums[j]) == k) {
++count;
}
}
}
return count;
}
#include <iostream>
int main() {
std::vector<int> nums1 = {1, 2, 2, 1};
int k1 = 1;
std::cout << "Example 1: " << countKDifference(nums1, k1) << std::endl; // Should output 4
std::vector<int> nums2 = {1, 3};
int k2 = 3;
std::cout << "Example 2: " << countKDifference(nums2, k2) << std::endl; // Should output 0
std::vector<int> nums3 = {3, 2, 1, 5, 4};
int k3 = 2;
std::cout << "Example 3: " << countKDifference(nums3, k3) << std::endl; // Should output 3
return 0;
}
This code first defines the function countKDifference which implements the described algorithm to count the pairs with absolute difference k. The main function demonstrates the usage with example inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?