K-diff Pairs in an Array — LeetCode 532 Python Solution

MediumArrayHash TableTwo PointersBinary SearchSorting
Problem
#532
Reading time
2 min

The problem

Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: 0 <= i, j < nums.length i != j |nums[i] - nums[j]| == k Notice that |val| denotes the absolute value of val.

Example

Input
nums = [3,1,4,1,5], k = 2
Output
2
Explanation
There are two 2-diff pairs in the array, (1, 3) and (3, 5).

Python solution

Python
class Solution:
    def findPairs(self, nums: List[int], k: int) -> int:
        ans = set()
        vis = set()
        for x in nums:
            if x - k in vis:
                ans.add(x - k)
            if x + k in vis:
                ans.add(x)
            vis.add(x)
        return len(ans)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 532. K-diff Pairs in an Array is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 532. K-diff Pairs in an Array?
LeetCode 532. K-diff Pairs in an Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 532. K-diff Pairs in an Array?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 532. K-diff Pairs in an Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 532. K-diff Pairs in an Array cover?
LeetCode 532. K-diff Pairs in an Array is tagged Array, Hash Table, Two Pointers, Binary Search and Sorting 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