K-diff Pairs in an Array — LeetCode 532 Python Solution
- Problem
- #532
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.