Skip to content

Commit 2a224f4

Browse files
author
Ram swaroop
committed
coded + unit tested
1 parent 215f956 commit 2a224f4

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package me.ramswaroop.arrays;
2+
3+
import java.util.Arrays;
4+
import java.util.HashSet;
5+
6+
/**
7+
* Created by IntelliJ IDEA.
8+
*
9+
* @author: ramswaroop
10+
* @date: 10/18/15
11+
* @time: 8:40 PM
12+
*/
13+
public class DuplicatesInArrayWithinKDistance {
14+
15+
/**
16+
* Finds duplicates in an unsorted array {@param a} which are
17+
* only k distance apart from each other.
18+
*
19+
* @param a
20+
* @param k
21+
* @return
22+
*/
23+
public static int[] findDuplicatesInArrayWithinKDistance(int[] a, int k) {
24+
int index = 0;
25+
int[] duplicates = new int[a.length];
26+
27+
HashSet<Integer> hashSet = new HashSet<>();
28+
29+
for (int i = 0; i < a.length; i++) {
30+
if (hashSet.contains(a[i])) {
31+
duplicates[index++] = a[i];
32+
} else {
33+
hashSet.add(a[i]);
34+
}
35+
36+
if (i >= k) {
37+
hashSet.remove(a[i - k]);
38+
}
39+
}
40+
41+
return Arrays.copyOf(duplicates, index);
42+
}
43+
44+
public static void main(String a[]) {
45+
System.out.println(Arrays.toString(findDuplicatesInArrayWithinKDistance(new int[]{1, 2, 8, 1, 3, 4, 5, 6, 6, 7}, 3)));
46+
}
47+
}

0 commit comments

Comments
 (0)