# Find duplicates in O(n) time and O(1) extra space | Set 1

Last Updated : 16 Apr, 2024

Given an array of n elements that contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and use only constant memory space.

Note: The repeating element should be printed only once.

Example:

Input: n=7 , array[]={1, 2, 3, 6, 3, 6, 1}
Output: 1, 3, 6
Explanation: The numbers 1 , 3 and 6 appears more than once in the array.

Input : n = 5 and array[] = {1, 2, 3, 4 ,3}
Output: 3
Explanation: The number 3 appears more than once in the array.

This problem is an extended version of the following problem.
Find the two repeating elements in a given array

## Approach 1( Using hashmap):

Use the input array to store the frequency of each element. While Traversing the array, if an element x is encountered then check if its frequency is greater than 1 , then put it in the result array. if result array is empty return -1 else sort the array and return array.

Follow the steps to implement the approach:

1. Create an empty unordered map (hashmap) to store the frequency of each element in the array.
2. Iterate through the given array.
3. For each element in the array, increment its frequency count in the hashmap.
4. Iterate through the hashmap.
5. For each key-value pair in the hashmap, if the value (frequency count) is greater than 1, add the corresponding key (element) to the result vector.
6. If the result vector is empty after step 3, it means no duplicates were found. In this case, add -1 to the result vector.
7. Return the result vector containing duplicate elements or -1 if no duplicates were found.
C++ ```#include <bits/stdc++.h> using namespace std; vector<int> duplicates(long long arr[], int n) { // Step 1: Create an empty unordered map to store element frequencies unordered_map<long long, int> freqMap; vector<int> result; // Step 2: Iterate through the array and count element frequencies for (int i = 0; i < n; i++) { freqMap[arr[i]]++; } // Step 3: Iterate through the hashmap to find duplicates for (auto& entry : freqMap) { if (entry.second > 1) { result.push_back(entry.first); } } // Step 4: If no duplicates found, add -1 to the result if (result.empty()) { result.push_back(-1); } //step 5: sort the result sort(result.begin(),result.end()); // Step 6: Return the result vector containing duplicate elements or -1 return result; } int main() { long long a[] = {1, 6, 5, 2, 3, 3, 2}; int n = sizeof(a) / sizeof(a[0]); vector<int> duplicates_found = duplicates(a, n); cout << "Duplicate elements: "; for (int element : duplicates_found) { cout << element << " "; } cout << endl; return 0; } ``` Java ```import java.util.*; public class Main { public static List<Integer> duplicates(long[] arr) { // Step 1: Create an empty hashmap to store element frequencies Map<Long, Integer> freqMap = new HashMap<>(); List<Integer> result = new ArrayList<>(); // Step 2: Iterate through the array and count element frequencies for (long num : arr) { freqMap.put(num, freqMap.getOrDefault(num, 0) + 1); } // Step 3: Iterate through the hashmap to find duplicates for (Map.Entry<Long, Integer> entry : freqMap.entrySet()) { if (entry.getValue() > 1) { result.add(Math.toIntExact(entry.getKey())); } } // Step 4: If no duplicates found, add -1 to the result if (result.isEmpty()) { result.add(-1); } // Step 5: Sort the result Collections.sort(result); // Step 6: Return the result list containing duplicate elements or -1 return result; } public static void main(String[] args) { long[] a = {1, 6, 5, 2, 3, 3, 2}; List<Integer> duplicatesFound = duplicates(a); System.out.print("Duplicate elements: "); for (int element : duplicatesFound) { System.out.print(element + " "); } System.out.println(); } } ``` Python3 ```def duplicates(arr): # Step 1: Create an empty dictionary to store element frequencies freq_map = {} result = [] # Step 2: Iterate through the array and count element frequencies for num in arr: freq_map[num] = freq_map.get(num, 0) + 1 # Step 3: Iterate through the dictionary to find duplicates for key, value in freq_map.items(): if value > 1: result.append(key) # Step 4: If no duplicates found, add -1 to the result if not result: result.append(-1) # Step 5: Sort the result result.sort() # Step 6: Return the result list containing duplicate elements or -1 return result if __name__ == "__main__": a = [1, 6, 5, 2, 3, 3, 2] duplicates_found = duplicates(a) print("Duplicate elements:", end=" ") for element in duplicates_found: print(element, end=" ") print() ``` C# ```using System; using System.Collections.Generic; using System.Linq; class Program { static List<int> Duplicates(long[] arr) { // Step 1: Create an empty dictionary to store element frequencies Dictionary<long, int> freqMap = new Dictionary<long, int>(); List<int> result = new List<int>(); // Step 2: Iterate through the array and count element frequencies foreach (long num in arr) { if (freqMap.ContainsKey(num)) freqMap[num]++; else freqMap[num] = 1; } // Step 3: Iterate through the dictionary to find duplicates foreach (var entry in freqMap) { if (entry.Value > 1) result.Add((int)entry.Key); } // Step 4: If no duplicates found, add -1 to the result if (result.Count == 0) result.Add(-1); // Step 5: Sort the result result.Sort(); // Step 6: Return the result list containing duplicate elements or -1 return result; } static void Main(string[] args) { long[] a = { 1, 6, 5, 2, 3, 3, 2 }; List<int> duplicatesFound = Duplicates(a); Console.Write("Duplicate elements: "); foreach (int element in duplicatesFound) { Console.Write(element + " "); } Console.WriteLine(); } } ``` JavaScript ```function duplicates(arr) { // Step 1: Create an empty object to store element frequencies const freqMap = {}; const result = []; // Step 2: Iterate through the array and count element frequencies for (let num of arr) { freqMap[num] = (freqMap[num] || 0) + 1; } // Step 3: Iterate through the object to find duplicates for (let key in freqMap) { if (freqMap[key] > 1) { result.push(Number(key)); } } // Step 4: If no duplicates found, add -1 to the result if (result.length === 0) { result.push(-1); } // Step 5: Sort the result result.sort((a, b) => a - b); // Step 6: Return the result array containing duplicate elements or -1 return result; } const a = [1, 6, 5, 2, 3, 3, 2]; const duplicatesFound = duplicates(a); console.log("Duplicate elements: " + duplicatesFound.join(" ")); ```

Output
```Duplicate elements: 2 3
```

Time Complexity: O(n), Only two traversals are needed. So the time complexity is O(n).

Auxiliary Space: O(n), The extra space is used for the array to be returned .

## Approach 2( by modification in the array):

Iterate through the array, for each element, increment its frequency marker at arr[element % n] by n. Traverse the modified array, if an element’s value divided by n is greater than 1, add its index to result indicating a duplicate. If no duplicates found, append -1 to result. Return the result vector.

Follow the steps to implement the approach:

1. Iterate through the array, calculating the index for each element as `arr[i] % n`, where `arr[i]` is the current element and` n` is the size of the array.
2. Increment the value at the calculated index by `n` to mark the frequency of the corresponding element.
3. Traverse the modified array again after completing the initial traversal.
4. For each element, calculate its frequency by dividing the value at the current index by `n`.
5. If the calculated frequency is greater than 1, add the index to the result vector, indicating a duplicate element.
6. If no duplicates are found during the traversal, append -1 to the result vector.
7. Return the result vector containing duplicate elements or -1 if no duplicates were found.
C++ ```#include <iostream> #include <vector> using namespace std; vector<int> duplicates(long long arr[], int n) { vector<int> result; // Step 1: Iterate through the array to mark frequencies for (int i = 0; i < n; i++) { // Calculate the index where the frequency needs to be stored int index = arr[i] % n; // Increment the value at the calculated index by n, marking the frequency arr[index] += n; } // Step 2: Traverse the modified array to find duplicate elements bool found = false; for (int i = 0; i < n; i++) { // Calculate the frequency of the current element if (arr[i] / n > 1) { // If frequency is greater than 1, add the index to the result vector result.push_back(i); found = true; } } // Step 3: If no duplicates found, add -1 to the result if (!found) { result.push_back(-1); } return result; } int main() { long long a[] = {1,2,3,3,2 ,6, 5, 2, 3, 3, 2}; int n = sizeof(a) / sizeof(a[0]); // Call the duplicates function to find duplicate elements vector<int> duplicates_found = duplicates(a, n); // Output the results cout << "Duplicate elements: "; for (int element : duplicates_found) { cout << element << " "; } cout << endl; return 0; } ``` Java ```import java.util.ArrayList; import java.util.List; public class Main { public static List<Integer> duplicates(long[] arr) { List<Integer> result = new ArrayList<>(); // Step 1: Iterate through the array to mark frequencies for (int i = 0; i < arr.length; i++) { // Calculate the index where the frequency needs to be stored int index = (int) (arr[i] % arr.length); // Increment the value at the calculated index by n, marking the frequency arr[index] += arr.length; } // Step 2: Traverse the modified array to find duplicate elements boolean found = false; for (int i = 0; i < arr.length; i++) { // Calculate the frequency of the current element if (arr[i] / arr.length > 1) { // If frequency is greater than 1, add the index to the result list result.add(i); found = true; } } // Step 3: If no duplicates found, add -1 to the result if (!found) { result.add(-1); } return result; } public static void main(String[] args) { long[] a = {1, 6, 5, 2, 3, 3, 2}; // Call the duplicates function to find duplicate elements List<Integer> duplicatesFound = duplicates(a); // Output the results System.out.print("Duplicate elements: "); for (int element : duplicatesFound) { System.out.print(element + " "); } System.out.println(); } } ``` Python3 ```def duplicates(arr): result = [] # Step 1: Iterate through the array to mark frequencies for i in range(len(arr)): # Calculate the index where the frequency needs to be stored index = arr[i] % len(arr) # Increment the value at the calculated index by n, marking the frequency arr[index] += len(arr) # Step 2: Traverse the modified array to find duplicate elements found = False for i in range(len(arr)): # Calculate the frequency of the current element if arr[i] // len(arr) > 1: # If frequency is greater than 1, add the index to the result list result.append(i) found = True # Step 3: If no duplicates found, add -1 to the result if not found: result.append(-1) return result a = [1, 6, 5, 2, 3, 3, 2] # Call the duplicates function to find duplicate elements duplicates_found = duplicates(a) # Output the results print("Duplicate elements:", end=" ") for element in duplicates_found: print(element, end=" ") print() ``` C# ```using System; using System.Collections.Generic; class MainClass { public static List<int> Duplicates(long[] arr) { List<int> result = new List<int>(); // Step 1: Iterate through the array to mark frequencies for (int i = 0; i < arr.Length; i++) { // Calculate the index where the frequency needs to be stored int index = (int)(arr[i] % arr.Length); // Increment the value at the calculated index by n, marking the frequency arr[index] += arr.Length; } // Step 2: Traverse the modified array to find duplicate elements bool found = false; for (int i = 0; i < arr.Length; i++) { // Calculate the frequency of the current element if (arr[i] / arr.Length > 1) { // If frequency is greater than 1, add the index to the result list result.Add(i); found = true; } } // Step 3: If no duplicates found, add -1 to the result if (!found) { result.Add(-1); } return result; } public static void Main(string[] args) { long[] a = {1, 6, 5, 2, 3, 3, 2}; // Call the duplicates function to find duplicate elements List<int> duplicatesFound = Duplicates(a); // Output the results Console.Write("Duplicate elements: "); foreach (int element in duplicatesFound) { Console.Write(element + " "); } Console.WriteLine(); } } ``` JavaScript ```function duplicates(arr) { let result = []; // Step 1: Iterate through the array to mark frequencies for (let i = 0; i < arr.length; i++) { // Calculate the index where the frequency needs to be stored let index = arr[i] % arr.length; // Increment the value at the calculated index by n, marking the frequency arr[index] += arr.length; } // Step 2: Traverse the modified array to find duplicate elements let found = false; for (let i = 0; i < arr.length; i++) { // Calculate the frequency of the current element if (arr[i] / arr.length > 1) { // If frequency is greater than 1, add the index to the result list result.push(i); found = true; } } // Step 3: If no duplicates found, add -1 to the result if (!found) { result.push(-1); } return result; } let a = [1, 6, 5, 2, 3, 3, 2]; // Call the duplicates function to find duplicate elements let duplicatesFound = duplicates(a); // Output the results process.stdout.write("Duplicate elements: "); for (let element of duplicatesFound) { process.stdout.write(element + " "); } console.log(); ```

Output
```Duplicate elements: 2 3
```

Time Complexity: O(n), Only two traversals are needed. If the answer to be return should in ascending order, then in that case we will have to sort the list and complexity will become O(n logn).

Auxiliary Space: O(1). The extra space is used only for the array to be returned.

Previous
Next