Similar Problems

Similar Problems not available

K Diff Pairs In An Array - Leetcode Solution

Companies:

  • adobe
  • amazon

LeetCode:  K Diff Pairs In An Array Leetcode Solution

Difficulty: Medium

Topics: hash-table binary-search two-pointers array sorting  

Problem Statement:

Given an array nums of n integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

Solution Approach:

We can solve this problem using a Hash Map (or Hash Set). We can iterate through each element in the array, and check if its corresponding k-diff element is present in the Hash Map. If it is present, we mark it as a valid pair and move forward.

We can also keep track of the already seen elements in the array using another Hash Map (or Hash Set). This will enable us to avoid counting the same pair again.

Algorithm:

  1. Initialize a Hash Map (let's call it count) and a Hash Set (let's call it seen).
  2. Iterate through each element (let's call it num) in the array.
  3. Check if there exists an element (let's call it num-k) such that num - num-k = k, and num-k is already present in the seen Hash Set. If yes, add the pair (num, num-k) to the count Hash Map.
  4. Check if there exists an element (let's call it num+k) such that num+k = k, and num+k is already present in the seen Hash Set. If yes, add the pair (num, num+k) to the count Hash Map.
  5. Add the current element num to the seen Hash Set.
  6. Repeat steps 2-5 for all elements in the array.
  7. Return the size of the count Hash Map.

Python Code:

class Solution: def findPairs(self, nums: List[int], k: int) -> int: count = {} seen = set() for num in nums: if num - k in seen: count[(num-k, num)] = 1 if num + k in seen: count[(num, num+k)] = 1 seen.add(num) return len(count)

K Diff Pairs In An Array Solution Code

1