Skip to content
This repository was archived by the owner on Dec 19, 2023. It is now read-only.

Commit 55b6dac

Browse files
committed
Add problem 532
1 parent 19d4357 commit 55b6dac

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

algorithms/532/README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
## 532. K-diff Pairs in an Array
2+
3+
Given an array of 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**.
4+
5+
**Example 1:**
6+
<pre>
7+
<b>Input:</b> [3, 1, 4, 1, 5], k = 2
8+
<b>Output:</b> 2
9+
<b>Explanation:</b> There are two 2-diff pairs in the array, (1, 3) and (3, 5).
10+
Although we have two 1s in the input, we should only return the number of unique pairs.
11+
</pre>
12+
13+
**Example 2:**
14+
<pre>
15+
<b>Input:</b> [1, 2, 3, 4, 5], k = 1
16+
<b>Output:</b> 4
17+
<b>Explanation:</b> There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and
18+
(4, 5).
19+
</pre>
20+
21+
**Example 3:**
22+
<pre>
23+
<b>Input:</b> [1, 3, 1, 5, 4], k = 0
24+
<b>Output:</b> 1
25+
<b>Explanation:</b> There is one 0-diff pair in the array, (1, 1).
26+
</pre>
27+
28+
**Note:**
29+
30+
1. The pairs (i, j) and (j, i) count as the same pair.
31+
2. The length of the array won't exceed 10,000.
32+
3. All the integers in the given input belong to the range: [-1e7, 1e7].

algorithms/532/solution.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package main
2+
3+
// Time and space complexity, O(n) where n is size of the array
4+
func findPairs(nums []int, k int) int {
5+
if k < 0 {
6+
return 0
7+
}
8+
countMap := make(map[int]int, len(nums))
9+
for _, n := range nums {
10+
countMap[n]++
11+
}
12+
var c int
13+
for n, count := range countMap {
14+
if 0 < k {
15+
if 0 < countMap[n+k] {
16+
c++
17+
}
18+
} else if 1 < count {
19+
c++
20+
}
21+
}
22+
return c
23+
}

0 commit comments

Comments
 (0)