Skip to content

Latest commit

 

History

History
72 lines (51 loc) · 2.81 KB

287.Find_the_Duplicate_Number(Medium).md

File metadata and controls

72 lines (51 loc) · 2.81 KB

287. Find the Duplicate Number (Medium)

Date and Time: Jul 31, 2024, 22:59 (EST)

Link: https://leetcode.com/problems/find-the-duplicate-number/


Question:

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 uses 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 <= 10^5

  • 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.


Walk-through:

This question can be converted into Linked-list question. We can think of the elements in nums to represent the index of nums, because we are guaranteed that [1, n] and at most n + 1 integers.

Then, we can use Floyd's Tortoise and Hare Algorithm to find the cycle by having fast = nums[nums[fast]] and slow = nums[slow] pointers. Next, we intialize slow2 = 0 and we run the while loop again until slow = slow2, and return slow the repeated number.


Python Solution:

class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        fast, slow = 0, 0
        while True:
            fast, slow = nums[nums[fast]], nums[slow]
            if fast == slow:
                break
        slow2 = 0
        while True:
            slow, slow2 = nums[slow], nums[slow2]
            if slow == slow2:
                return slow

Time Complexity: $O(n)$
Space Complexity: $O(1)$


CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms