Find All Duplicates in an Array

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given an integer array nums of length n where all integers are in the range [1, n] and each integer appears once or twice, return an array of all integers that appear twice.

You must write an algorithm that runs in O(n) time and uses only O(1) extra space.

Examples

Example 1:

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

Output: [3, 2]

Explanation: 3 and 2 each appear twice.

Example 2:

Input: nums = [1, 1, 2]

Output: [1]

Explanation: 1 appears twice.

Example 3:

Input: nums = [1]

Output: []

Constraints

  • n == nums.length
  • 1 <= n <= 10^5
  • 1 <= nums[i] <= n
  • Each element appears once or twice
Source: Cyclic Sort pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle