Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
Example 1:
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
Constraints:
1 <= nums.length <= 105-109 <= nums[i] <= 1090 <= k <= 105When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a row of items and you want to check if any two identical items are too close to each other. The brute force approach involves checking every possible pair of items in the row to see if they match and measuring the distance between them.
Here's how the algorithm would work step-by-step:
def contains_nearby_duplicate(number_list, max_distance):
# Check every possible pair to find duplicates within the allowed distance limit
for outer_index in range(len(number_list)):
for inner_index in range(outer_index + 1, len(number_list)):
if number_list[outer_index] == number_list[inner_index]:
# Calculate the exact distance between the duplicate items
current_distance = inner_index - outer_index
if current_distance <= max_distance:
return True
# Return false if no duplicate pairs meet the distance requirement
return FalseThe optimal approach uses a moving memory window to keep track of recently seen items as you scan through the list. By checking your memory every time you look at a new item, you can instantly tell if you have seen a matching item recently enough to satisfy the distance requirement.
Here's how the algorithm would work step-by-step:
def contains_nearby_duplicate(array_of_numbers, max_allowed_distance):
seen_items_notebook = {}
# We scan through the items one by one to check our notebook against distance constraints.
for current_index, current_item in enumerate(array_of_numbers):
if current_item in seen_items_notebook and current_index - seen_items_notebook[current_item] <= max_allowed_distance:
return True
# We update the notebook with the most recent position of the item for future distance checks.
seen_items_notebook[current_item] = current_index
# If we finish scanning without finding any matching items within the allowed distance, no duplicate exists.
return False| Case | How to Handle |
|---|---|
| Empty array or single element array | The loop will not find any duplicate pairs and will safely return false. |
| K is larger than the array length | The sliding window or hash map simply checks all available elements without throwing bounds errors. |
| K is zero | An index cannot have an absolute difference less than or equal to zero with a distinct index, correctly returning false. |
| Multiple identical values closer than K | Updating the hash map with the most recent index ensures we find the minimum distance violation and return true. |
| Duplicates exist but their indices differ by more than K | The sliding window or index check restricts valid pairs to distance k, correctly ignoring duplicates outside the window. |
| Array contains negative numbers and zeros | Hash maps and array lookups treat negative numbers and zeros the same as positive integers without altering index arithmetic. |
| Very large arrays with maximum constraints | A linear scan using a hash map or sliding window of size k runs in O N time complexity to prevent time limit exceeded errors. |
| No valid duplicates within distance K exist | The algorithm completes the full iteration without returning true and defaults to returning false. |