Duplicates Within K Distance in Array/Matrix/2D Array - Algorithms and Problem SolvingAlgorithms and Problem Solving
This is a classical sliding window problem where we need to check if an element is duplicated in a window of size k that contains elements within k indices away. So, we basically need a data structure to maintain the sliding window along with efficiently checking if an element exists in the window. Which data structure to use? Obviously we choose a hash set.
In order to maintain the sliding window we initially create a hashset of size k from first k indices. Then for each index in the array we slide the window by removing the first element of the window from the hashset and adding the current element to the hashset. Meanwhile we keep testing for any duplicates. Below is the implementation of the above idea which tests if a given array contains duplicates within k distance in O(n) time and O(k) space.
Given an array of integer, find duplicates which are within k indices away. Find duplicates within K manhattan distance away in a matrix or 2D array. Return true or false if such elements exists.
For example, a=[1, 2, 3, 1, 3, 5] then for
k ≤ 1
return false as no duplicates in k index away. For k=2 we return true as 3 is repeated in 2 distance away. Similarly for k ≥ 3
we return true as both 1 and 3 are repeated.
In case of 2D array or matrix, for example,
mat = 1 2 3 4 k = 1 Output: false Explanation: no duplicates within 1 manhattan distance. mat = 1 1 3 4 k = 0 Output: false Explanation: within 0 distance there can't be any duplicates trivially mat = 1 1 3 4 k = 1 Output: true Explanation: 1 is duplicated within 1 manhattan distance.Duplicates Within k indices away in an Array
This is a classical sliding window problem where we need to check if an element is duplicated in a window of size k that contains elements within k indices away. So, we basically need a data structure to maintain the sliding window along with efficiently checking if an element exists in the window. Which data structure to use? Obviously we choose a hash set.
In order to maintain the sliding window we initially create a hashset of size k from first k indices. Then for each index in the array we slide the window by removing the first element of the window from the hashset and adding the current element to the hashset. Meanwhile we keep testing for any duplicates. Below is the implementation of the above idea which tests if a given array contains duplicates within k distance in O(n) time and O(k) space.
public static boolean checkDuplicateWithinK(int[] a, int k){ int n = a.length; k = Math.min(n, k); Set<Integer> slidingWindow = new HashSet<Integer>(k); //create initial wiindow of size k int i; for(i = 0; i < k; i++){ if(slidingWindow.contains(a[i])){ return true; } slidingWindow.add(a[i]); } //now slide for(i = k; i < n; i++){ slidingWindow.remove(a[i-k]); if(slidingWindow.contains(a[i])){ return true; } slidingWindow.add(a[i]); } return false; }http://www.geeksforgeeks.org/check-given-array-contains-duplicate-elements-within-k-distance/
static
boolean
checkDuplicatesWithinK(
int
arr[],
int
k)
{
// Creates an empty hashset
HashSet<Integer> set =
new
HashSet<>();
// Traverse the input array
for
(
int
i=
0
; i<arr.length; i++)
{
// If already present n hash, then we found
// a duplicate within k distance
if
(set.contains(arr[i]))
return
true
;
// Add this item to hashset
set.add(arr[i]);
// Remove the k+1 distant item
if
(i >= k)
set.remove(arr[i-k]);
}
return
false
;
}
Duplicates Within k distance away in a 2D Array or Matrix
time: the O(matrix-size) which is a upper bound.
space: O(matrix-size) which is also upper bound, i can shrink the hash when loop through the matrix by removing the rows which is above i-k, but it may not gain too much, which depends on k.
How could we extend the solution for a matrix where distance is measured based on Manhattan Distance between two elements in the grid? Note that this is still a sliding window problem. But the size of the sliding window is dynamic unlike fixed equal to k in case of array where we have only one element at a distance k from any position in the sliding window. This is because of the property of Manhattan Distance in case of matrix/2d array grid where we can have many grid positions that are of same distance away from a given position. So, an element can get duplicated in many positions of the matrix that have the distance.
In order to handle multiple position per value we can use a HashMap as the sliding window that maps a value to the set of positions it is contained within the sliding window. As window size is not fixed so we can’t deterministically build the window. Instead we traverse each element in the grid and check whether current element is within k manhattan distance away from each of the elements in the elements having the same value. If yes then we have a duplicate. Otherwise we update the sliding window by removing all elements that are already k rows away (all elements in a row more than k distance far from current non-duplicate can’t be part of the sliding window of k manhattan distance) and adding the current element.
Below is a O(n*m*k) time and O(n*k) space algorithm where nxm is the matrix dimensions.
public static boolean checkDuplicateWithinK(int[][] mat, int k){ class Cell{ int row; int col; public Cell(int r, int c){ this.row = r; this.col = c; } } int n = mat.length; int m = mat[0].length; k = Math.min(k, n*m); //map from distance to cell postions of the matrix Map<Integer, Set<Cell>> slidingWindow = new HashMap<Integer, Set<Cell>>(); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(slidingWindow.containsKey(mat[i][j])){ for(Cell c : slidingWindow.get(mat[i][j])){ int manhattanDist = Math.abs(i - c.row)+Math.abs(j - c.col); if(manhattanDist <= k){ return true; } if(i - c.row > k){ slidingWindow.remove(c); } } slidingWindow.get(mat[i][j]).add(new Cell(i, j)); } else{ slidingWindow.put(mat[i][j], new HashSet<Cell>()); slidingWindow.get(mat[i][j]).add(new Cell(i, j)); } } } return false; }http://blueocean-penn.blogspot.com/2015/07/find-duplicate-elements-k-indices-away.html
time: the O(matrix-size) which is a upper bound.
space: O(matrix-size) which is also upper bound, i can shrink the hash when loop through the matrix by removing the rows which is above i-k, but it may not gain too much, which depends on k.
public static boolean determineKIndices(int[][] matrix, int k){
Map<Integer, Set<Pos>> store = new HashMap<Integer, Set<Pos>>();
for(int row=0; row<matrix.length; row++){
for(int col=0; col<matrix[0].length; col++){
int val = matrix[row][col];
if(store.containsKey(val)){
Set<Pos> set = store.get(val);
for(Pos p: set){
if(Math.abs(p.getRow() - row) + Math.abs(p.getCol()-col) <=k ){
return true;
}
if(row - p.getRow() >k)
set.remove(p);
if(row - p.getRow() >k)
set.remove(p);
}
set.add(new Pos(row, col));
}else{
Set<Pos> set = new HashSet<Pos>();
set.add(new Pos(row, col));
store.put(val, set);
}
}
}
return false;
}
Read full article from Duplicates Within K Distance in Array/Matrix/2D Array - Algorithms and Problem SolvingAlgorithms and Problem Solving