InterviewHubPRO
Section Overview
Q44

Question 44 of 100

Part 5: Linked Lists & Fast-Slow Pointers (37 - 45)

44%
DSA Patterns (Multi-Lang)•Part 5: Linked Lists & Fast-Slow Pointers (37 - 45)

Find the Duplicate Number.

In Simple Words: Floyd's Tortoise and Hare Cycle Detection on implicit graph i -> nums[i].

  1. Intersection: slow = nums[slow], fast = nums[nums[fast]] until they meet.
  2. Find entrance: Reset slow2 = 0, move slow and slow2 at 1 step/iteration until they collide.
  • Time: $O(N)$ | Space: $O(1)$
Multi-Language Solutions
Switch tabs or choose All
def findDuplicate(nums: list[int]) -> int:
    slow, fast = 0, 0
    # Phase 1: Detect cycle
    while True:
        slow = nums[slow]
        fast = nums[nums[fast]]
        if slow == fast:
            break
    # Phase 2: Find cycle entrance
    slow2 = 0
    while True:
        slow = nums[slow]
        slow2 = nums[slow2]
        if slow == slow2:
            return slow