← Questions
Contains duplicate within distance K
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's technical phone screen, last asked Aug 2025. It tests hash maps and sliding window.
Given an integer array nums and an integer k, decide whether two equal values sit at most k positions apart. If they do, also return the smallest gap among all such pairs.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
nearby_duplicate(nums: list[int], k: int) -> list— returns[found, gap]:foundisTrueif somei != jhasnums[i] == nums[j]and|i - j| <= k, andgapis the smallest such|i - j|, or-1when none exists.
Example
nearby_duplicate([1, 2, 3, 1], 3) -> [True, 3]
nearby_duplicate([1, 0, 1, 1], 1) -> [True, 1] # indices 2 and 3
nearby_duplicate([1, 2, 3, 1, 2, 3], 2) -> [False, -1] # equal values are 3 apart
nearby_duplicate([], 0) -> [False, -1]
Constraints
-
0 <= len(nums) <= 10^5,0 <= k <= len(nums),-10^9 <= nums[i] <= 10^9. - O(n) time.
Clarifying questions
- Is the gap
<= kor< k? - Do you want only yes or no, or the indices or the gap too?
- Can
kbe 0? (Then no pair qualifies.)
What a strong answer covers
- A map from value to its last index. Comparing each element only with the previous occurrence of its value is enough, because the closest equal pair is always two consecutive occurrences.
- O(n) time and O(n) space first. Then the follow-up: cut the space to O(k) by keeping only the last
kvalues in a set or map, removingnums[i - k]as the window moves, so stale entries never pile up. - Stopping early when the gap is 1.
- Tests:
k = 0, all values equal, a duplicate just outside the window.
Follow-ups
- Use at most O(k) extra space.
- Values only need to be close, not equal:
|nums[i] - nums[j]| <= tas well (use buckets of widtht + 1, or a sorted window). - The array is a stream. Report the first such pair as soon as it appears.
Where it's asked
- Meta · Technical phone screen · Last asked Aug 202545 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted
What it tests
hash maps · sliding window
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
