VOOZH about

URL: https://www.geeksforgeeks.org/dsa/duplicates-elements-in-an-array/

⇱ Duplicates in a Limited Range and Limited Repetition Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Duplicates in a Limited Range and Limited Repetition Array

Last Updated : 4 Jun, 2026

Given an array arr[] of integers of size n, where each element is in the range 1 to n and each element can occur at most twice, find all elements that appear twice in the array.

Examples:

Input: arr[] = [2, 3, 1, 2, 3]
Output: [2, 3]
Explanation: 2 and 3 occur twice in the given array.

Input: arr[] = [3, 1, 2]
Output: []
Explanation: There is no repeating element in the array, so the output is empty.

[Naive Approach] Using Nested Loops - O(n2) Time and O(1) Space

The main Idea is to iterate through each element and check if it already exists in the result. If not, we scan the rest of the array to see if it appears again. If it does, we add it to the result.


Output
2 3 

[Better Approach] Using Frequency Array - O(n) Time and O(n) Space

The main Idea is to traverse the array once and count the occurrences of each element using a frequency array. Then, we iterate through the array to collect elements whose frequency 2, indicating they are duplicates.


Output
3 2 

[Expected Approach] Negative Marking approach - O(n) Time and O(1) Space

The main Idea is to iterate over the array and use the value of each element as an index (after subtracting 1). If the element at that index is positive, we negate it to mark the number as visited. If it's already negative, it means we've seen it before, so we add it to the result. This avoids extra space and works in linear time.

Step by step approach:

  • Traverse the array once, using each value arr[i] to compute an index idx = abs(arr[i]) - 1.
  • Check the value at arr[idx]:
    => If it is positive, mark it as visited by setting arr[idx] = -arr[idx].
    => If it is already negative, it means arr[i] has been seen before, so it's a duplicate.
  • Add such duplicate values to the result list.

Output
2 3 
Comment
Article Tags:
Article Tags: