11. Duplicate in an array.

11. Duplicate in an array.


Problem link :- click here
Note :- We have to include "Stdlib.h" library to use "abs" function.



C code

//Duplicate in an array
#include<stdio.h>
#include<stdlib.h>

void print_repeating(int arr[], int n)
{
    int i;
    for(i=0; i<n; i++)
    {
        if(arr[abs(arr[i])] >= 0)
            arr[abs(arr[i])] = -arr[abs(arr[i])];
        else
            printf("\t%d",abs(arr[i]));
    }
}

void main()
{
    int arr[30];
    int n, i;

    printf("Enter the size of the array\n");
    scanf("%d",&n);
    printf("Enter the elements of the array\n");
    for(i=0; i<n; i++)
        scanf("%d",&arr[i]);

    printf("Given Array\n");
    for(i=0; i<n; i++)
        printf("\t%d",arr[i]);
    printf("\n");

    printf("\n\nDuplicates elements in array are :- \n");
    print_repeating(arr, n);
}

Java code

//Duplicate
package programs;

import java.util.*;
import java.lang.*;

public class Array__11
{

	static void print_duplicate(int arr[], int n)
	{
		for(int i=0; i<n; i++)
		{
			if(arr[Math.abs(arr[i])] >= 0)
				arr[Math.abs(arr[i])]  = -arr[Math.abs(arr[i])];
			else
				System.out.print( Math.abs(arr[i])  + " " );
		}
	}
	
	public static void main(String[] args)
	{
		int array[] = new int[20];
		int n, i;
		
		Scanner s = new Scanner(System.in);
		System.out.print("Enter the size of the array :");
		n = s.nextInt();
		System.out.println("Enter the elements of the array :");
		for(i=0; i<n; i++)
			array[i] = s.nextInt();
		System.out.println("Given Array :");
		print_array(array, n);
		
		System.out.println("\n\nDuplicate elements in the array are :");
		print_duplicate(array, n);
	}

	static void print_array(int arr[], int n)
	{
		for(int i=0; i<n; i++)
			System.out.print(arr[i] + " ");
	}
}

Time complexity :- O(n)
Space complexity :- O(1)



Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree