Reduce the array such that each element appears at most 2 times
Last Updated :
16 Oct, 2023
Given a sorted array arr of size N, the task is to reduce the array such that each element can appear at most two times.
Examples:
Input: arr[] = {1, 2, 2, 2, 3}
Output: {1, 2, 2, 3}
Explanation:
Remove 2 once, as it occurs more than 2 times.
Input: arr[] = {3, 3, 3}
Output: {3, 3}
Explanation:
Remove 3 once, as it occurs more than 2 times.
Approach: This can be solved with the help of two pointer algorithm.
- Start traversing the array from the left and keep two pointers.
- One pointer (let’s say i) is used to iterate the array.
- And the second pointer (let’s say st) moves forward to find the next unique element. The element in i appears more than twice.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
void removeDuplicates( int arr[], int n)
{
int st = 0;
for ( int i = 0; i < n; i++) {
if (i < n - 2
&& arr[i] == arr[i + 1]
&& arr[i] == arr[i + 2])
continue ;
else {
arr[st] = arr[i];
st++;
}
}
cout << "{" ;
for ( int i = 0; i < st; i++) {
cout << arr[i];
if (i != st - 1)
cout << ", " ;
}
cout << "}" ;
}
int main()
{
int arr[]
= { 1, 1, 1, 2,
2, 2, 3, 3,
3, 3, 3, 3,
4, 5 };
int n = sizeof (arr)
/ sizeof (arr[0]);
removeDuplicates(arr, n);
return 0;
}
|
Java
class GFG
{
static void removeDuplicates( int arr[], int n)
{
int st = 0 ;
for ( int i = 0 ; i < n; i++) {
if (i < n - 2
&& arr[i] == arr[i + 1 ]
&& arr[i] == arr[i + 2 ])
continue ;
else {
arr[st] = arr[i];
st++;
}
}
System.out.print( "{" );
for ( int i = 0 ; i < st; i++) {
System.out.print(arr[i]);
if (i != st - 1 )
System.out.print( ", " );
}
System.out.print( "}" );
}
public static void main(String[] args)
{
int arr[] = { 1 , 1 , 1 , 2 ,
2 , 2 , 3 , 3 ,
3 , 3 , 3 , 3 ,
4 , 5 };
int n = arr.length;
removeDuplicates(arr, n);
}
}
|
Python3
def removeDuplicates(arr, n) :
st = 0 ;
for i in range (n) :
if (i < n - 2 and arr[i] = = arr[i + 1 ]
and arr[i] = = arr[i + 2 ]) :
continue ;
else :
arr[st] = arr[i];
st + = 1 ;
print ( "{" ,end = "")
for i in range (st) :
print (arr[i],end = "");
if (i ! = st - 1 ) :
print ( ", " ,end = "");
print ( "}" ,end = "");
if __name__ = = "__main__" :
arr = [ 1 , 1 , 1 , 2 ,
2 , 2 , 3 , 3 ,
3 , 3 , 3 , 3 ,
4 , 5 ];
n = len (arr);
removeDuplicates(arr, n);
|
C#
using System;
class GFG
{
static void removeDuplicates( int []arr, int n)
{
int st = 0;
for ( int i = 0; i < n; i++) {
if (i < n - 2
&& arr[i] == arr[i + 1]
&& arr[i] == arr[i + 2])
continue ;
else {
arr[st] = arr[i];
st++;
}
}
Console.Write( "{" );
for ( int i = 0; i < st; i++) {
Console.Write(arr[i]);
if (i != st - 1)
Console.Write( ", " );
}
Console.Write( "}" );
}
public static void Main(String[] args)
{
int []arr = { 1, 1, 1, 2,
2, 2, 3, 3,
3, 3, 3, 3,
4, 5 };
int n = arr.Length;
removeDuplicates(arr, n);
}
}
|
Javascript
<script>
function removeDuplicates(arr,n)
{
let st = 0;
for (let i = 0; i < n; i++) {
if (i < n - 2
&& arr[i] == arr[i + 1]
&& arr[i] == arr[i + 2])
continue ;
else {
arr[st] = arr[i];
st++;
}
}
document.write( "{" );
for (let i = 0; i < st; i++) {
document.write(arr[i]);
if (i != st - 1)
document.write( ", " );
}
document.write( "}" );
}
let arr = [ 1, 1, 1, 2,
2, 2, 3, 3,
3, 3, 3, 3,
4, 5 ];
let n = arr.length;
removeDuplicates(arr, n);
</script>
|
Output
{1, 1, 2, 2, 3, 3, 4, 5}
Time complexity: O(N)
Space complexity: O(1)
Another Approach: Using Counter() function
- Calculate the frequency of all elements using a counter function.
- Take an empty list.
- Traverse the array.
- If the frequency of any element is greater than or equal to 2, make its frequency 1 and append it to the list.
- If the frequency of any element is equal to 1, take its frequency 0 and append it to the list.
- Print the list.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void removeDuplicates( int arr[], int n)
{
unordered_map< int , int > mm;
vector< int > temp;
for ( int i=0;i<n;i++)
{
mm[arr[i]]++;
}
for ( int i=0;i<n;i++)
{
if (mm[arr[i]]>=2)
{
temp.push_back(arr[i]);
mm[arr[i]]=1;
}
else if (mm[arr[i]]==1)
{
temp.push_back(arr[i]);
mm[arr[i]]=0;
}
}
for ( auto x:temp)
{
cout<<x<< " " ;
}
}
int main() {
int arr[] = {1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5};
int n = 14;
removeDuplicates(arr, n);
}
|
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class GFG {
public static void removeDuplicates( int [] arr, int n) {
List<Integer> l = new ArrayList<>();
Map<Integer, Integer> freq = new HashMap<>();
for ( int i = 0 ; i < n; i++) {
if (freq.containsKey(arr[i])) {
freq.put(arr[i], freq.get(arr[i]) + 1 );
} else {
freq.put(arr[i], 1 );
}
}
for ( int i = 0 ; i < n; i++) {
if (freq.get(arr[i]) >= 2 ) {
freq.put(arr[i], 1 );
l.add(arr[i]);
} else if (freq.get(arr[i]) == 1 ) {
l.add(arr[i]);
freq.put(arr[i], 0 );
}
}
for ( int i : l) {
System.out.print(i + " " );
}
}
public static void main(String[] args) {
int [] arr = { 1 , 1 , 1 , 2 , 2 , 2 , 3 , 3 , 3 , 3 , 3 , 3 , 4 , 5 };
int n = arr.length;
removeDuplicates(arr, n);
}
}
|
Python3
from collections import Counter
def removeDuplicates(arr, n):
freq = Counter(arr)
l = []
for i in range (n):
if (freq[arr[i]] > = 2 ):
freq[arr[i]] = 1
l.append(arr[i])
elif (freq[arr[i]] = = 1 ):
l.append(arr[i])
freq[arr[i]] = 0
for i in l:
print (i, end = " " )
if __name__ = = "__main__" :
arr = [ 1 , 1 , 1 , 2 ,
2 , 2 , 3 , 3 ,
3 , 3 , 3 , 3 ,
4 , 5 ]
n = len (arr)
removeDuplicates(arr, n)
|
C#
using System;
using System.Collections.Generic;
class Program
{
static void RemoveDuplicates( int [] arr, int n)
{
Dictionary< int , int > dict = new Dictionary< int , int >();
List< int > temp = new List< int >();
for ( int i = 0; i < n; i++)
{
if (dict.ContainsKey(arr[i]))
dict[arr[i]]++;
else
dict.Add(arr[i], 1);
}
for ( int i = 0; i < n; i++)
{
if (dict[arr[i]] >= 2)
{
temp.Add(arr[i]);
dict[arr[i]] = 1;
}
else if (dict[arr[i]] == 1)
{
temp.Add(arr[i]);
dict[arr[i]] = 0;
}
}
foreach ( int x in temp)
{
Console.Write(x + " " );
}
}
static void Main( string [] args)
{
int [] arr = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5 };
int n = 14;
RemoveDuplicates(arr, n);
}
}
|
Javascript
function removeDuplicates(arr, n) {
const freqMap = {};
const temp = [];
for (let i = 0; i < n; i++) {
freqMap[arr[i]] = (freqMap[arr[i]] || 0) + 1;
}
for (let i = 0; i < n; i++) {
if (freqMap[arr[i]] >= 2) {
temp.push(arr[i]);
freqMap[arr[i]] = 1;
} else if (freqMap[arr[i]] === 1) {
temp.push(arr[i]);
freqMap[arr[i]] = 0;
}
}
console.log(temp);
}
const arr = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5];
removeDuplicates(arr, arr.length);
|
Time complexity: O(N)
Auxiliary Space: O(N)
Approach 3: Recursive Approach
1. Take a pointer j = 0 to keep track of the current position in the vector.
2. Iterate over the input vector using a pointer i.
3. If the current element is not a duplicate or appears at most two times, update it to the vector using the pointer j.
4. Increment the count of consecutive occurrences of the current element.
5. Recursively call the function with the next element in the vector.
6. Return the final value of the j to indicate the number of elements in the vector and then print the up to j elements which is our answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int removeDuplicates(vector< int >& arr, int n, int i, int j, int count) {
if (i == n) {
return j;
}
if (i > 0 && arr[i] == arr[i - 1]) {
count++;
} else {
count = 1;
}
if (count <= 2) {
arr[j] = arr[i];
j++;
}
return removeDuplicates(arr, n, i + 1, j, count);
}
int main() {
vector< int > arr = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5 };
int n = arr.size();
int st = removeDuplicates(arr, n, 0, 0, 0);
cout << "{" ;
for ( int i = 0; i < st; i++) {
cout << arr[i];
if (i != st - 1)
cout << ", " ;
}
cout << "}" ;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static int
removeDuplicates(ArrayList<Integer> arr, int n, int i,
int j, int count)
{
if (i == n) {
return j;
}
if (i > 0 && arr.get(i) == arr.get(i - 1 )) {
count++;
}
else {
count = 1 ;
}
if (count <= 2 ) {
arr.set(j, arr.get(i));
j++;
}
return removeDuplicates(arr, n, i + 1 , j, count);
}
public static void main(String[] args)
{
ArrayList<Integer> arr
= new ArrayList<Integer>(Arrays.asList(
1 , 1 , 1 , 2 , 2 , 2 , 3 , 3 , 3 , 3 , 3 , 3 , 4 , 5 ));
int n = arr.size();
int st = removeDuplicates(arr, n, 0 , 0 , 0 );
System.out.print( "{" );
for ( int i = 0 ; i < st; i++) {
System.out.print(arr.get(i));
if (i != st - 1 )
System.out.print( ", " );
}
System.out.print( "}" );
}
}
|
Python3
def remove_duplicates(arr, n, i, j, count):
if i = = n:
return j
if i > 0 and arr[i] = = arr[i - 1 ]:
count + = 1
else :
count = 1
if count < = 2 :
arr[j] = arr[i]
j + = 1
return remove_duplicates(arr, n, i + 1 , j, count)
arr = [ 1 , 1 , 1 , 2 , 2 , 2 , 3 , 3 , 3 , 3 , 3 , 3 , 4 , 5 ]
n = len (arr)
st = remove_duplicates(arr, n, 0 , 0 , 0 )
print ( "[" , end = "")
for i in range (st):
print (arr[i], end = "")
if i ! = st - 1 :
print ( ", " , end = "")
print ( "]" )
|
C#
using System;
using System.Collections.Generic;
class Program {
static List< int > RemoveDuplicates(List< int > list)
{
List< int > result = new List< int >();
int count = 0;
foreach ( int num in list)
{
if (result.Count == 0
|| num != result[result.Count - 1]) {
result.Add(num);
count = 1;
}
else if (count < 2) {
result.Add(num);
count++;
}
}
return result;
}
static void Main()
{
List< int > numbers
= new List< int >{ 1, 1, 1, 2, 2, 2, 3,
3, 3, 3, 3, 3, 4, 5 };
List< int > uniqueList = RemoveDuplicates(
numbers);
Console.Write( "{" );
for ( int i = 0; i < uniqueList.Count; i++) {
Console.Write(uniqueList[i]);
if (i < uniqueList.Count - 1)
Console.Write( ", " );
}
Console.WriteLine( "}" );
}
}
|
Javascript
function removeDuplicates(arr) {
const result = [];
let count = 0;
for (const num of arr) {
if (result.length === 0 || num !== result[result.length - 1]) {
result.push(num);
count = 1;
} else if (count < 2) {
result.push(num);
count++;
}
}
return result;
}
const inputArray = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5];
const uniqueArray = removeDuplicates(inputArray);
console.log(`[${uniqueArray.join( ', ' )}]`);
|
Output
{1, 1, 2, 2, 3, 3, 4, 5}
Time complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...