MEDIUM NC#42 Linked List / Floyd's Algorithm

287. Find the Duplicate Number

๐Ÿ“– Problem

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.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation

๐Ÿ’ก Approach

  • โ†’ Treat array as linked list where nums[i] points to nums[nums[i]]
  • โ†’ This creates a cycle because of duplicate
  • โ†’ Use Floyd's cycle detection (fast/slow pointers)
  • โ†’ When cycle found, find entrance (the duplicate)
  • โ†’ Time: O(n), Space: O(1)

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขTreat array as linked list where nums[i] points to nums[nums[i]]
  • โ€ขThis creates a cycle because of duplicate
  • โ€ขUse Floyd's cycle detection (fast/slow pointers)

Common Pitfalls

  • โ€ขWhen cycle found, find entrance (the duplicate)
  • โ€ขTime: O(n), Space: O(1)

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
findDuplicate([1,3,4,2,2]);
Expected:
2
Test Case 2
Not run
Input:
findDuplicate([3,1,3,4,2]);
Expected:
3
Test Case 3
Not run
Input:
findDuplicate([3,3,3,3,3]);
Expected:
3

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit