Open In App

Duplicates in an array in O(n) and by using O(1) extra space

Last Updated : 24 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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(" "));

Output
1 2 3 

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



Next Article
Article Tags :
Practice Tags :

Similar Reads