Duplicates in an array in O(n) and by using O(1) extra space
Last Updated :
24 Dec, 2024
Given an array arr[] of n elements that contains elements from 0 to n-1, with any of these numbers appearing any number of times. The task is to find the repeating numbers.
Note: The repeating element should be printed only once.
Example:
Input: n = 7, arr[] = [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, arr[] = [1, 2, 3, 4 ,3]
Output: 3
Explanation: The number 3 appears more than once in the array.
Please refer to Duplicates in an array in O(n) and by using O(n) extra space for implementation of naive approach.
Approach:
The basic idea is based on the hash map to solve the problem. But, the numbers in the array are from 0 to n-1, and the input array has length n. So, the input array itself can be used as a hash map. While traversing the array, if an element a is encountered then increase the value of a % n'th element by n. The frequency can be retrieved by dividing the a % n'th element by n.
Note: This approach works because all elements are in the range from 0 to n-1 and arr[i]/n would be greater than 1 only if a value "i" has appeared more than once.
C++
// C++ code to find duplicates in an array
// in O(1) space
#include <bits/stdc++.h>
using namespace std;
vector<int> findDuplicates(vector<int> &arr) {
int n = arr.size();
// First check all the values that are
// present in an array then go to that
// values as indexes and increment by
// the size of array
for (int i = 0; i < n; i++) {
int index = arr[i] % n;
arr[index] += n;
}
// Now check which value exists more
// than once by dividing with the size
// of array
vector<int> result;
for (int i = 0; i < n; i++) {
if ((arr[i] / n) >= 2)
result.push_back(i);
}
return result;
}
int main() {
vector<int> arr = {2, 3, 1, 2, 3, 1, 6};
vector<int> duplicates = findDuplicates(arr);
for (int element : duplicates) {
cout << element << " ";
}
return 0;
}
Java
// Java code to find duplicates in an array
// in O(1) space
import java.util.*;
class GfG {
static int[] findDuplicates(int[] arr) {
int n = arr.length;
// First check all the values that are
// present in an array then go to that
// values as indexes and increment by
// the size of array
for (int i = 0; i < n; i++) {
int index = arr[i] % n;
arr[index] += n;
}
// Now check which value exists more
// than once by dividing with the size
// of array
List<Integer> result = new ArrayList<>();
for (int i = 0; i < n; i++) {
if ((arr[i] / n) >= 2) {
result.add(i);
}
}
// If no duplicates found, return array with -1
if (result.isEmpty()) {
result.add(-1);
}
// Convert list to array and return
return result.stream().mapToInt(i -> i).toArray();
}
public static void main(String[] args) {
int[] arr = { 2, 3, 1, 2, 3, 1, 6 };
int[] duplicates = findDuplicates(arr);
for (int element : duplicates) {
System.out.print(element + " ");
}
}
}
Python
# Python code to find duplicates in an array
# in O(1) space
def findDuplicates(arr):
n = len(arr)
# First check all the values that are
# present in an array then go to that
# values as indexes and increment by
# the size of array
for i in range(n):
index = arr[i] % n
arr[index] += n
# Now check which value exists more
# than once by dividing with the size
# of array
result = []
for i in range(n):
if (arr[i] // n) >= 2:
result.append(i)
return result
if __name__ == "__main__":
arr = [2, 3, 1, 2, 3, 1, 6]
duplicates = findDuplicates(arr)
print(" ".join(map(str, duplicates)))
C#
// C# code to find duplicates in an array
// in O(1) space
using System;
using System.Collections.Generic;
class GfG {
static int[] FindDuplicates(int[] arr) {
int n = arr.Length;
// First check all the values that are
// present in an array then go to that
// values as indexes and increment by
// the size of array
for (int i = 0; i < n; i++) {
int index = arr[i] % n;
arr[index] += n;
}
// Now check which value exists more
// than once by dividing with the size
// of array
List<int> result = new List<int>();
for (int i = 0; i < n; i++) {
if ((arr[i] / n) >= 2) {
result.Add(i);
}
}
// If no duplicates found, return an array with -1
if (result.Count == 0) {
result.Add(-1);
}
return result.ToArray();
}
static void Main(string[] args) {
int[] arr = { 2, 3, 1, 2, 3, 1, 6 };
int[] duplicates = FindDuplicates(arr);
foreach (int element in duplicates) {
Console.Write(element + " ");
}
}
}
JavaScript
// JavaScript code to find duplicates in an array
// in O(1) space
function findDuplicates(arr) {
let n = arr.length;
// First check all the values that are
// present in an array then go to that
// values as indexes and increment by
// the size of array
for (let i = 0; i < n; i++) {
let index = arr[i] % n;
arr[index] += n;
}
// Now check which value exists more
// than once by dividing with the size
// of array
let result = [];
for (let i = 0; i < n; i++) {
if (Math.floor(arr[i] / n) >= 2) {
result.push(i);
}
}
return result;
}
// Driver code
let arr = [2, 3, 1, 2, 3, 1, 6];
let duplicates = findDuplicates(arr);
console.log(duplicates.join(" "));
Time Complexity: O(n), Only two traversals are needed. So the time complexity is O(n)
Auxiliary Space: O(1). As no extra space is needed, so the space complexity is constant
Similar Reads
Find duplicate in an array in O(n) and by using O(1) extra space Given an array arr[] containing n integers where each integer is between 1 and (n-1) (inclusive). There is only one duplicate element, find the duplicate element in O(n) time complexity and O(1) space.Examples : Input : arr[] = {1, 4, 3, 4, 2} Output : 4Input : arr[] = {1, 3, 2, 1}Output : 1Approach
13 min read
Duplicates in an array in O(n) time and by using O(1) extra space | Set-3 Given an array of n elements which 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 using only constant memory space. It is required that the order in which elements repeat should be maintained. If there is no repeatin
10 min read
Find duplicates in O(n) time and O(n) extra space Given an array arr[] of n elements that contains elements from 0 to n-1, with any of these numbers appearing any number of times. The task is to find the repeating numbers.Note: The repeating element should be printed only once.Example: Input: n = 7, arr[] = [1, 2, 3, 6, 3, 6, 1]Output: 1, 3, 6Expla
10 min read
Remove duplicates from a string in O(1) extra space Given a string str of lowercase characters, the task is to remove duplicates and return a resultant string without modifying the order of characters in the original string. Examples: Input: str = "geeksforgeeks" Output: geksfor Input: str = "characters" Output: chartes Approach: The idea is to use b
13 min read
Remove duplicate elements in an Array using STL in C++ Given an array, the task is to remove the duplicate elements from the array using STL in C++ Examples: Input: arr[] = {2, 2, 2, 2, 2} Output: arr[] = {2} Input: arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5} Output: arr[] = {1, 2, 3, 4, 5} Approach: This can be done using set in standard template library. Set
2 min read
Find the duplicate characters in a string in O(1) space Given a string str, the task is to find all the duplicate characters present in a given string in lexicographical order without using any additional data structure. Examples: Input: str = "geeksforgeeks" Output: e g k s Explanation: Frequency of character 'g' = 2 Frequency of character 'e' = 4 Frequ
10 min read
Count frequencies of all elements in array in O(1) extra space and O(n) time Given an unsorted array of n integers that can contain integers from 1 to n. Some elements can be repeated multiple times and some other elements can be absent from the array. Count the frequency of all elements that are present and print the missing elements. Examples: Input: arr[] = {2, 3, 3, 2, 5
15+ min read
Find duplicates in constant array with elements 0 to N-1 in O(1) space Given a constant array of n elements which contains elements from 1 to n-1, with any of these numbers appearing any number of times. Find any one of these repeating numbers in O(n) and using only constant memory space. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 3} Output : 3 As the given array is
12 min read
Find duplicates in an Array with values 1 to N using counting sort Given a constant array of N elements which contain elements from 1 to N - 1, with any of these numbers appearing any number of times.Examples: Input: N = 5, arr[] = {1, 3, 4, 2, 2} Output: 2 Explanation: 2 is the number occurring more than once.Input: N = 5, arr[] = {3, 1, 3, 4, 2} Output: 3 Explana
11 min read
Find Duplicates of array using bit array You have an array of N numbers, where N is at most 32,000. The array may have duplicate entries and you do not know what N is. With only 4 Kilobytes of memory available, how would print all duplicate elements in the array ?. Examples: Input : arr[] = {1, 5, 1, 10, 12, 10} Output : 1 10 1 and 10 appe
8 min read