Leetcode 2006: Count Number of Pairs With Absolute Difference K

grid47
grid47
Exploring patterns and algorithms
Apr 20, 2024 5 min read

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.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array nums and an integer k.
Example: nums = [3, 5, 2, 6, 7], k = 3
Constraints:
• 1 <= nums.length <= 200
• 1 <= nums[i] <= 100
• 1 <= k <= 99
Output: Return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.
Example: 2
Constraints:
Goal: The goal is to count the number of pairs with an absolute difference of k.
Steps:
• 1. Create a frequency count of the elements in the array.
• 2. For each element x, check if x + k or x - k exists in the array.
• 3. Add the count of valid pairs for each element.
• 4. Return the total count of valid pairs.
Goal: The input array is between 1 and 200 elements long, with values ranging from 1 to 100 for each element.
Steps:
• 1 <= nums.length <= 200
• 1 <= nums[i] <= 100
• 1 <= k <= 99
Assumptions:
• The solution should be efficient given the constraints.
• Handling of duplicate elements is necessary to avoid over-counting pairs.
Input: nums = [3, 5, 2, 6, 7], k = 3
Explanation: The valid pairs with an absolute difference of 3 are (3, 6) and (5, 2). Thus, the output is 2.

Input: nums = [1, 1, 3, 5], k = 2
Explanation: The valid pair with an absolute difference of 2 is (3, 5). Hence, the output is 1.

Input: nums = [8, 2, 5, 6, 9], k = 4
Explanation: The valid pairs with an absolute difference of 4 are (8, 4) and (5, 9). The output is 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus