Given an array or a 2D matrix of integers, determine if any value appears at least twice such that the two occurrences are within a distance of at most k (indices for array, Manhattan distance for matrix). Return true if such a duplicate exists, otherwise return false.
classSolution {
public:bool containsNearbyDuplicate(vector<vector<int>>& mat, int k) {
int n = mat.size(), m = mat[0].size();
unordered_map<int, vector<pair<int, int>>> pos;
for (int i =0; i < n; ++i) {
for (int j =0; j < m; ++j) {
int val = mat[i][j];
for (auto& p : pos[val]) {
if (abs(i - p.first) + abs(j - p.second) <= k) return true;
}
pos[val].emplace_back(i, j);
}
}
return false;
}
};
import java.util.*;
classSolution {
publicbooleancontainsNearbyDuplicate(int[][] mat, int k) {
int n = mat.length, m = mat[0].length;
Map<Integer, List<int[]>> pos =new HashMap<>();
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
int v = mat[i][j];
if (!pos.containsKey(v)) pos.put(v, new ArrayList<>());
for (int[] p : pos.get(v)) {
if (Math.abs(i - p[0]) + Math.abs(j - p[1]) <= k) returntrue;
}
pos.get(v).add(newint[]{i, j});
}
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defcontainsNearbyDuplicate(self, mat: list[list[int]], k: int) -> bool:
from collections import defaultdict
pos: dict[int, list[tuple[int, int]]] = defaultdict(list)
n, m = len(mat), len(mat[0])
for i in range(n):
for j in range(m):
v = mat[i][j]
for pi, pj in pos[v]:
if abs(i - pi) + abs(j - pj) <= k:
returnTrue pos[v].append((i, j))
returnFalse
⏰ Time complexity: O(n * m * d), where d is the number of previous occurrences of a value (worst case O(nmk) if all values are the same, but usually much less).
🧺 Space complexity: O(n * m), for storing positions.