BC202 - Editorial

#PROBLEM LINK:

Practice
Contest

Author: Ayush Nagal

#DIFFICULTY:
EASY

#PREREQUISITES:
Array

#PROBLEM:
Given a sorted array arr, remove the duplicates from arr such that each element appears only once and display the new array.

#EXPLANATION:
This problem can be easily solved in O(n). While traversing the array, if arr[i] matches with arr[i-1], we have to delete it. Instead of deleting it and shifting the elements, we can simply store a large negative value in its place as shown in the following code snippet:

for(int i=1;i<n;i++)
{
    if(arr[i]==arr[i-1])
    arr[i-1]=-10000;
}

Now we have removed the duplicates and we need to print the elements of the array:

for(int i=0;i<n;i++)
{
    if(arr[i]==-10000)
    continue;
    cout<<arr[i]<<" ";
}

#AUTHOR’S SOLUTION:
Author’s solution can be found here.

1 Like