Taro Logo

Contains Duplicate

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+20
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.2K views
Topics:
Arrays

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Example 1:

Input: nums = [1,2,3,1]

Output: true

Explanation:

The element 1 occurs at the indices 0 and 3.

Example 2:

Input: nums = [1,2,3,4]

Output: false

Explanation:

All elements are distinct.

Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]

Output: true

Constraints:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109

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 size of the input array `nums`, and are there any memory constraints I should keep in mind?
  2. What range of values can the integers inside the array `nums` span?
  3. How should the function handle edge cases like an empty array or an array with only a single element?
  4. Is the input array guaranteed to be mutable, or should I treat it as read-only?
  5. Are there any constraints on the data types, or can I assume all elements are standard 32-bit signed integers?

Brute Force Solution

Approach

Imagine you are holding a collection of items and need to figure out if any two of them are identical. The brute force approach involves exhaustively comparing every single item against every other item in the collection to see if any match.

Here's how the algorithm would work step-by-step:

  1. Pick up the first item in your collection.
  2. Compare this first item against every other item that comes after it, one by one.
  3. If you find any item that is an exact match to the first item, you immediately know a duplicate exists and you are done.
  4. If none of the remaining items match the first item, put it aside.
  5. Move on to the second item and compare it against all the items that come after it.
  6. Continue this exhaustive process of picking an item and comparing it to every subsequent item until you have checked all possible pairs.
  7. If you finish checking every single combination without finding any matches, you can safely conclude that there are no duplicates.

Code Implementation

def contains_duplicate_brute_force(collection_items):
    # Iterate through every item to establish a baseline for comparison against the rest of the list
    for current_index in range(len(collection_items)):
        
        for comparison_index in range(current_index + 1, len(collection_items)):
            # Compare the currently selected item against every subsequent item to detect any exact match
            if collection_items[current_index] == collection_items[comparison_index]:
                return True
                
    # Exhausted all possible pairs without finding a match, so we conclude no duplicates exist
    return False

Big(O) Analysis

Time Complexity
O(n²) – For each of the n items in the collection, the strategy requires comparing it against every single subsequent item to check for a match. The first item is compared against n-1 items, the second against n-2 items, and this pattern continues down to the final items. When we sum these comparisons across all items, the total operations approximate n * n/2, which simplifies to a quadratic time complexity of O(n²).
Space Complexity
O(1) – The brute force approach described relies entirely on comparing elements in place without allocating any additional data structures like temporary lists or hash maps. The only memory consumed consists of a few primitive variables used for tracking loop indices during the nested comparisons. Because these variables require a constant amount of memory regardless of the input size, the extra space remains fixed. As N grows, the auxiliary space does not scale, resulting in a constant complexity of O(1).

Optimal Solution

Approach

Instead of comparing every single item against all the others one by one, the optimal approach uses a special tracking tool like a personal checklist. As you review each item, you check off what you have seen so far, allowing you to instantly spot a repeat the moment you encounter it.

Here's how the algorithm would work step-by-step:

  1. Start with a blank personal checklist where you can write down items as you review them.
  2. Begin looking through your collection of items one by one.
  3. For the current item you are holding, check your personal checklist to see if it is already written down there.
  4. If the item is already on your checklist, you have found a duplicate, so you can stop right there and confirm the answer.
  5. If the item is not on your checklist, add it to your checklist so you remember seeing it.
  6. Move on to the next item and repeat the checking process.
  7. If you finish reviewing everything without finding a match on your checklist, confirm that all items are completely unique.

Code Implementation

def contains_duplicate(collection_of_items):
    # Initialize an empty checklist to track items we have already encountered.
    personal_checklist = set()
    
    for current_item in collection_of_items:
        # Check if the item is already on our checklist to instantly spot duplicates.
        if current_item in personal_checklist:
            return True
        
        # Add the item to our checklist so we remember seeing it for future checks.
        personal_checklist.add(current_item)
        
    # If we finish checking everything without matches, confirm items are unique.
    return False

Big(O) Analysis

Time Complexity
O(n) – To determine if there are duplicates, we iterate through the collection of n items one by one. During each step, we perform a lookup and a potential insertion in our personal checklist, which both operate in constant time on average. As we examine all n items sequentially, the total number of operations grows linearly with the size of the input. This scales proportionally as n operations, which simplifies to O(n).
Space Complexity
O(N) – The optimal solution utilizes a Hash Set, referred to in the explanation as a personal checklist, to track the unique elements encountered so far. In the worst-case scenario where all elements are distinct, this checklist will store every single item from the input. Therefore, the extra memory required grows directly in proportion to the input size, where N is the total number of elements. This yields a linear auxiliary space complexity of O(N).

Edge Cases

Empty array or single element array
How to Handle:
Return false immediately because duplicate values are impossible with fewer than two elements.
Array with exactly two elements, one duplicate and one unique
How to Handle:
The hash set or sorting approach correctly identifies the matching pair and returns true.
Array with all identical elements
How to Handle:
The second element encountered will already exist in the set, triggering an immediate true return.
Array containing negative numbers and zeros alongside positives
How to Handle:
Hash sets and sorting algorithms handle negative numbers and zeros seamlessly without any special offset logic.
Extremely large arrays with maximum constraints
How to Handle:
A hash set approach ensures linear time complexity of O(n) to prevent time limit exceedance.
Extremely large arrays with memory constraints
How to Handle:
A sorting approach can be used instead of a hash set to achieve O(1) extra space complexity at the cost of O(n log n) time.
Inputs containing extreme boundary integer values
How to Handle:
Standard hash set implementations natively support full integer range keys without overflow or collision issues.
0/75 completed