PIXELBANKv9.1.0
Menu

Find All Duplicates in Array

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 all integers that appear twice.

You must run in O(n) time with O(1) extra space. Output as space-separated sorted integers.

Example:

Input:
4,3,2,7,8,2,3,1
Output:
2 3
Reasoning:
  • We start by iterating over the input array nums and for each number, we use its absolute value as an index to mark the presence of that number.
  • When we encounter a number, we check if the value at its corresponding index is negative. If it's not, we mark it as negative to indicate that we've seen this number before.
  • We repeat this process for all numbers in the array. After that, we iterate over the array again to find the indices that are still positive, which correspond to the numbers that appear only once. The numbers that appear twice will have negative values at their corresponding indices.
  • Finally, we return the indices of the negative values (excluding the sign) in sorted order, which are the numbers that appear twice in the array: 22 and 33.

Constraints:

  • 1 <= n <= 10^5
  • 1 <= nums[i] <= n
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.