Count Number of Pairs With Absolute Difference K — LeetCode 2006 Python Solution

EasyArrayHash TableCounting
Problem
#2006
Pattern
Hash Map
Reading time
2 min

The problem

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 value of |x| is defined as: x if x >= 0.

Example

Input
nums = [1,2,2,1], k = 1
Output
4
Explanation
The pairs with an absolute difference of 1 are:

Python solution

Python
class Solution:
    def countKDifference(self, nums: List[int], k: int) -> int:
        n = len(nums)
        return sum(
            abs(nums[i] - nums[j]) == k for i in range(n) for j in range(i + 1, n)
        )

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(1) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2006. Count Number of Pairs With Absolute Difference K is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2006. Count Number of Pairs With Absolute Difference K?
LeetCode 2006. Count Number of Pairs With Absolute Difference K is rated Easy on LeetCode.
What is the time complexity of LeetCode 2006. Count Number of Pairs With Absolute Difference K?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 2006. Count Number of Pairs With Absolute Difference K?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2006. Count Number of Pairs With Absolute Difference K cover?
LeetCode 2006. Count Number of Pairs With Absolute Difference K is tagged Array, Hash Table and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview