Saturday, December 4, 2021
HomeTop Coding QuestionWrite a program to remove duplicate number in array .

Write a program to remove duplicate number in array .

Given a integer sorted array ,we have to remove duplicate number in an array.and print new array values.

Example:

input: arr[]={1, 1,2,2,3,4 };
output:1,2,3,4

Logic:

step 1-initialise i =0,j=0;
step 2-if adjacent element are not equal then just maintain index of array.
step 3-print the array value with new size.

Code-

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int arr[]={1,1,2,2,3,4};
    int n=sizeof(arr)/sizeof(arr[0]);
    int j=0;
    int i=0;
   
    for(i=0;i<n;i++)
    {
        if(arr[i]!=arr[i+1])
        {
            
            arr[j++]=arr[i];
            
        }
    }
    for(int i=0;i<j;i++)
    {
        cout<<arr[i]<<" ";
    }
    
    
}

Output:

1 2 3 4

Time complexity:0(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments