Taro Logo

Contains Duplicate II

#42 Most AskedEasy
Topics:
ArraysSliding Windows

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] <= 109
  • 0 <= k <= 105

Solution


Clarifying Questions

When 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:

  1. What is the expected range of values for the elements in the `nums` array and the integer `k`?
  2. How should the function behave if the input array `nums` is empty or contains fewer than two elements?
  3. Can `k` be larger than the length of the array `nums`, and if so, how should that be handled?
  4. Are there any constraints on memory usage, or is an O(N) space complexity acceptable?
  5. If there are multiple pairs of indices that satisfy the condition, does it matter which pair is found, as long as we return true?

Brute Force Solution

Approach

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:

  1. Pick the first item in your collection to start your investigation.
  2. Compare this chosen item with every single item that comes after it one by one.
  3. Whenever you find two identical items, measure the distance between them.
  4. Check if that distance is within your allowed limit.
  5. If the distance is within the limit, you have found a matching pair and can stop right there.
  6. If it is not within the limit, continue your search.
  7. If you run out of items to compare for your first choice, move on to the second item in the collection and repeat the entire process.
  8. Keep testing every possible pair until you either find a matching pair within the allowed distance or run out of pairs to check.

Code Implementation

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 False

Big(O) Analysis

Time Complexity
O(n²) – For each of the n items in the collection, the algorithm iterates through every single subsequent item to check for a duplicate and measure the distance. The outer loop runs n times, and the inner loop checks remaining items, performing roughly (n - 1), (n - 2), down to 1 comparisons. Summing these checks results in approximately n * n / 2 total operations. As n grows larger, constant factors are dropped, simplifying the overall time complexity to O(n²).
Space Complexity
O(1) – The provided plain English explanation describes a brute force approach where we only use a few scalar variables to track indices and loop counters, without creating any auxiliary data structures like hash maps or temporary lists. Regardless of the input size N, the extra memory required remains constant because we are just comparing items directly within the existing collection. Therefore, the auxiliary space complexity is O(1).

Optimal Solution

Approach

The 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:

  1. Start scanning through the items from the beginning to the end, one by one.
  2. As you look at each item, check your mental notebook to see if you have encountered this exact same item recently.
  3. If the item is already in your notebook, check how far apart your current position is from the last time you saw it.
  4. If the distance between the two matching items is small enough, you have successfully found a match and can immediately stop.
  5. If the item is not in your notebook, or if the previous matching item is too far away to matter, write down the current item and its position in your notebook.
  6. Make sure your notebook only remembers items that are close enough to your current position, erasing older memories that have fallen too far behind.
  7. Continue this process for the remaining items until you either find a valid match or run out of items to check.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n) – As we scan through the array of n elements from beginning to end, we perform constant-time lookup, insertion, and deletion operations inside our hash-based memory notebook. Each of the n items is processed at most once as the sliding window moves across the array. The total operations scale linearly with the number of elements, approximating c * n where c is a small constant factor. Simplifying this linear progression yields an overall time complexity of O(n).
Space Complexity
O(k) – To implement the notebook described in the algorithm, we use a hash map or a sliding window set to track the most recently seen items and their positions. In the worst-case scenario where no duplicates are found within the distance requirement, the notebook stores up to k items concurrently. As the maximum allowed distance k scales relative to the input size N, the auxiliary memory consumed by this structure grows proportionally to k.

Edge Cases

Empty array or single element array
How to Handle:
The loop will not find any duplicate pairs and will safely return false.
K is larger than the array length
How to Handle:
The sliding window or hash map simply checks all available elements without throwing bounds errors.
K is zero
How to Handle:
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
How to Handle:
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
How to Handle:
The sliding window or index check restricts valid pairs to distance k, correctly ignoring duplicates outside the window.
Array contains negative numbers and zeros
How to Handle:
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
How to Handle:
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
How to Handle:
The algorithm completes the full iteration without returning true and defaults to returning false.
0/245 completed