GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Ask a Question

 

Start Coding Today

   

GeeksQuiz

GeeksforGeeksIDE

Data Structures

Algorithms

Interview Experiences

C Programming

C++ Programming

Java Programming

GATE CS

Books

Find duplicates in O(n) time and O(1) extra space | Set 1 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.

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.

For example, let n = 10 and array will be { 4, 2, 4, 4, 2, 4, 1, 8, 3,8 };, the answer should be 2, 4 and 8.

 

package com.jay.algo.array;

public class PrintDuplicate {
	void printRepeating(int arr[], int size) {

		System.out.println("The repeating elements are : ");

		for (int i = 0; i < size; i++) {
			int curr = Math.abs(arr[i]);
			if (curr >= size) {
				curr = curr - size;
				if(curr>=size)
					curr = curr - size;
			}
			if (arr[curr] >= 0)
				arr[curr] = curr==0?-size*2 :-arr[curr];
			else {
				
				if (arr[curr] > -size || arr[curr]==-size*2) {
					
					System.out.print(curr + " ");
					arr[curr] = arr[curr] - size;
				}
			}

		}
	}

	/* Driver program to test the above function */
	public static void main(String[] args) {
		PrintDuplicate duplicate = new PrintDuplicate();
		int arr[] = { 0, 0, 4, 4, 2, 4, 1, 8, 3,8,11,11 };
		int arr_size = arr.length;
		duplicate.printRepeating(arr, arr_size);
		
	}
}

 

Time Complexity : O(n)
Auxiliary Space : O(1),

Above Algorithm is not correct, it restricted to positive value.

asked Feb 20 by Jay Tiwari 1
...