Taro Logo

Find the Duplicate Number

#6 Most AskedMedium
0 views
Topics:
ArraysTwo Pointers

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

There is only one repeated number in nums, return this repeated number.

You must solve the problem without modifying the array nums and using only constant extra space.

Example 1:

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

Example 2:

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

Example 3:

Input: nums = [3,3,3,3,3]
Output: 3

Constraints:

  • 1 <= n <= 105
  • nums.length == n + 1
  • 1 <= nums[i] <= n
  • All the integers in nums appear only once except for precisely one integer which appears two or more times.

Follow up:

  • How can we prove that at least one duplicate number must exist in nums?
  • Can you solve the problem in linear runtime complexity?

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. Are there any negative numbers or zeros in the array, or are all integers strictly within the range [1, n] as stated?
  2. Is the duplicate number guaranteed to appear only twice, or could it appear more than two times while all other numbers appear only once?
  3. Since the problem states there is only one repeated number, can I assume the input array is always valid and will always contain a duplicate according to the Pigeonhole Principle?
  4. Should I return the duplicate value itself, or its index in the array?
  5. Is it possible that the input array is modified if I use certain approaches, or is the constraint strictly 'no modification' under all circumstances?

Brute Force Solution

Approach

Imagine you have a group of items and you know at least one item appears more than once. The brute force approach is the most straightforward way to solve this by systematically comparing every single item against every other item until you find a match.

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

  1. Pick the very first item from your collection.
  2. Compare this chosen item against every other item in the collection one by one.
  3. If you ever find another item that is identical to the one you picked, you have found your duplicate and you are done.
  4. If the first item does not match any other item, move on to the second item in the collection.
  5. Repeat the process of comparing this new item against all the remaining items.
  6. Continue picking items one by one and checking them against all other items until a matching pair is discovered.

Code Implementation

def find_duplicate_number(collection_items):
    # Systematically check every item against all subsequent items to discover a repeating value
    for primary_index in range(len(collection_items)):

        for second_index in range(primary_index + 1, len(collection_items)):

            # A match confirms the current value appears more than once in our input dataset
            if collection_items[primary_index] == collection_items[second_index]:

                return collection_items[primary_index]

Big(O) Analysis

Time Complexity
O(n²) – For each of the n items in the collection, the brute force approach systematically compares that chosen item against every other item one by one. This nested pair checking means we perform roughly n minus 1 comparisons for the first item, n minus 2 for the second, and so on. Summing these comparisons across all elements leads to approximately n * n/2 total operations. As the input size n grows, this quadratic workload simplifies to O(n²).
Space Complexity
O(1) – The brute force approach described relies entirely on systematically comparing each item against the others using nested loops without allocating any additional data structures. Only a few primitive pointer variables are used to keep track of the current items being compared, meaning the extra memory required remains constant regardless of the input size N. Therefore, the auxiliary space complexity is strictly O(1).

Optimal Solution

Approach

Imagine everyone is walking in a path that eventually leads to a looped track where people just run in circles. The secret to finding the repeated person is to use two runners, one moving slowly and the other moving twice as fast, until they eventually meet each other.

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

  1. Send out two people to walk the path, with one taking single steps and the other taking double steps.
  2. Let them keep walking until the fast person catches up to the slow person, which is guaranteed to happen because of the loop.
  3. Once they meet up, leave the fast person where they are and bring someone new back to the very beginning of the entire path.
  4. Now, have the person from the beginning and the person who was waiting walk forward at the exact same speed, taking only single steps.
  5. Watch where they eventually bump into each other, as that exact meeting spot is the secret starting point of the loop.
  6. Declare that meeting spot as the repeated person you were looking for all along.

Code Implementation

def find_duplicate(sequence_of_numbers):
    # Floyd's cycle detection guarantees convergence when values map to indices.
    slow_runner = sequence_of_numbers[0]

    fast_runner = sequence_of_numbers[0]

    while True:
        slow_runner = sequence_of_numbers[slow_runner]

        fast_runner = sequence_of_numbers[sequence_of_numbers[fast_runner]]

        if slow_runner == fast_runner:
            break

    # Resetting one pointer to the start finds the cycle entry via path geometry.
    pointer_from_start = sequence_of_numbers[0]

    pointer_from_meeting = slow_runner

    while pointer_from_start != pointer_from_meeting:
        pointer_from_start = sequence_of_numbers[pointer_from_start]

        pointer_from_meeting = sequence_of_numbers[pointer_from_meeting]

    # The entry node of the cycle mathematically corresponds to the duplicate value.
    return pointer_from_start

Big(O) Analysis

Time Complexity
O(n) – The first phase uses a slow and a fast pointer that traverse the array indices until they meet, which takes at most n steps because the values form a functional graph with a cycle. The second phase resets one pointer to the start and moves both pointers at single-step speeds until they collide at the cycle entry point, requiring another n steps at most. Total operations scale linearly with the number of elements n, approximating 2n steps which simplifies to O(n).
Space Complexity
O(1) – The algorithm relies solely on two pointer variables acting as the slow and fast runners to navigate through the sequence without utilizing any dynamic data structures like hash maps or auxiliary arrays. Regardless of how large the input size N grows, the memory required to store these few pointer variables remains strictly constant. Therefore, the auxiliary space complexity is constant because no additional memory scales with the input size.

Edge Cases

Minimum valid input size of length two
How to Handle:
The cycle detection algorithm correctly handles the smallest possible array by pointing index 1 to itself or another valid position within the range.
Maximum possible constraint values up to hundred thousand elements
How to Handle:
The pointer-based Floyd's Cycle Finding algorithm runs in linear time and constant space, avoiding memory limits and timeouts.
Duplicate number appears multiple times in the array
How to Handle:
The linked list cycle approach inherently finds the entry point of the cycle regardless of the frequency of the duplicated value.
The duplicate number points to itself forming a self-loop
How to Handle:
The fast and slow pointers will immediately meet at this node, correctly identifying the duplicate without entering an infinite loop.
Values span the entire range from one to n without gaps except the duplicate
How to Handle:
The array acts as a valid functional graph where every index from zero to n points to a valid index, guaranteeing a well-defined cycle.
The duplicate value is the maximum possible value n
How to Handle:
Since all array values are bounded within the range one to n inclusive, the pointers will never exceed valid index bounds.
Zero values or negative numbers present in the input
How to Handle:
The problem constraints explicitly state all integers are within the range one to n inclusive, making out-of-range checks unnecessary.
Array modification restriction strictly enforced
How to Handle:
Using Floyd's Tortoise and Hare algorithm allows us to solve the problem in read-only mode, satisfying the constant space and immutable array constraints.
0/11 completed