Open in App
Not now

# Reduce the array such that each element appears at most 2 times

• Difficulty Level : Easy
• Last Updated : 02 Mar, 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.

1. Start traversing the array from the left and keep two pointers.
2. One pointer (let’s say i) is used to iterate the array.
3. 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

 `// C++ program to reduce the array` `// such that each element appears` `// at most 2 times`   `#include ` `using` `namespace` `std;`   `// Function to remove duplicates` `void` `removeDuplicates(``int` `arr[], ``int` `n)` `{` `    ``// Initialise 2nd pointer` `    ``int` `st = 0;`   `    ``// Iterate over the array` `    ``for` `(``int` `i = 0; i < n; i++) {`   `        ``if` `(i < n - 2` `            ``&& arr[i] == arr[i + 1]` `            ``&& arr[i] == arr[i + 2])` `            ``continue``;`   `        ``// Updating the 2nd pointer` `        ``else` `{` `            ``arr[st] = arr[i];` `            ``st++;` `        ``}` `    ``}`   `    ``cout << ``"{"``;` `    ``for` `(``int` `i = 0; i < st; i++) {` `        ``cout << arr[i];`   `        ``if` `(i != st - 1)` `            ``cout << ``", "``;` `    ``}` `    ``cout << ``"}"``;` `}`   `// Driver code` `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]);`   `    ``// Function call` `    ``removeDuplicates(arr, n);`   `    ``return` `0;` `}`

## Java

 `// Java program to reduce the array` `// such that each element appears` `// at most 2 times` `class` `GFG` `{`   `// Function to remove duplicates` `static` `void` `removeDuplicates(``int` `arr[], ``int` `n)` `{` `    ``// Initialise 2nd pointer` `    ``int` `st = ``0``;`   `    ``// Iterate over the array` `    ``for` `(``int` `i = ``0``; i < n; i++) {`   `        ``if` `(i < n - ``2` `            ``&& arr[i] == arr[i + ``1``]` `            ``&& arr[i] == arr[i + ``2``])` `            ``continue``;`   `        ``// Updating the 2nd pointer` `        ``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(``"}"``);` `}`   `// Driver code` `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;`   `    ``// Function call` `    ``removeDuplicates(arr, n);` `}` `}`   `// This code is contributed by sapnasingh4991`

## Python3

 `# Python3 program to reduce the array ` `# such that each element appears ` `# at most 2 times `   `# Function to remove duplicates ` `def` `removeDuplicates(arr, n) : `   `    ``# Initialise 2nd pointer ` `    ``st ``=` `0``; `   `    ``# Iterate over the array ` `    ``for` `i ``in` `range``(n) :`   `        ``if` `(i < n ``-` `2` `and` `arr[i] ``=``=` `arr[i ``+` `1``] ` `            ``and` `arr[i] ``=``=` `arr[i ``+` `2``]) :` `            ``continue``; `   `        ``# Updating the 2nd pointer ` `        ``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``=``""); `   `# Driver code ` `if` `__name__ ``=``=` `"__main__"` `: `   `    ``arr ``=` `[ ``1``, ``1``, ``1``, ``2``, ` `            ``2``, ``2``, ``3``, ``3``, ` `            ``3``, ``3``, ``3``, ``3``, ` `            ``4``, ``5` `]; `   `    ``n ``=` `len``(arr);` `    `  `    ``# Function call ` `    ``removeDuplicates(arr, n); `   `# This code is contributed by Yash_R`

## C#

 `// C# program to reduce the array` `// such that each element appears` `// at most 2 times` `using` `System;`   `class` `GFG` `{` ` `  `// Function to remove duplicates` `static` `void` `removeDuplicates(``int` `[]arr, ``int` `n)` `{` `    ``// Initialise 2nd pointer` `    ``int` `st = 0;` ` `  `    ``// Iterate over the array` `    ``for` `(``int` `i = 0; i < n; i++) {` ` `  `        ``if` `(i < n - 2` `            ``&& arr[i] == arr[i + 1]` `            ``&& arr[i] == arr[i + 2])` `            ``continue``;` ` `  `        ``// Updating the 2nd pointer` `        ``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(``"}"``);` `}` ` `  `// Driver code` `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;` ` `  `    ``// Function call` `    ``removeDuplicates(arr, n);` `}` `}`   `// This code is contributed by sapnasingh4991`

## Javascript

 ``

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 ` `using` `namespace` `std;` `void` `removeDuplicates(``int` `arr[],``int` `n)` `{` `      ``//unordered_map to store frequency` `      ``unordered_map<``int``,``int``> mm;` `      `  `      ``//this vector will contain the final elements form array` `      ``vector<``int``> temp;` `  `  `      ``//iterating over array to store frequency of each element` `      ``for``(``int` `i=0;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<

## Java

 `/*package whatever //do not write package name here */`   `import` `java.util.ArrayList;` `import` `java.util.Arrays;` `import` `java.util.HashMap;` `import` `java.util.List;` `import` `java.util.Map;`   `class` `GFG {` `    `    `// Function to remove duplicates` `public` `static` `void` `removeDuplicates(``int``[] arr, ``int` `n) {` `    ``// Taking empty list` `    ``List l = ``new` `ArrayList<>();` `    ``Map 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``) {` `            ``// Making frequency to 1` `            ``freq.put(arr[i], ``1``);` `            ``l.add(arr[i]);` `        ``} ``else` `if` `(freq.get(arr[i]) == ``1``) {` `            ``// Making frequency to 0` `            ``// and appending to list` `            ``l.add(arr[i]);` `            ``freq.put(arr[i], ``0``);` `        ``}` `    ``}`   `    ``// Printing the list` `    ``for` `(``int` `i : l) {` `        ``System.out.print(i + ``" "``);` `    ``}` `}`   `// Driver code` `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;`   `    ``// Function call` `    ``removeDuplicates(arr, n);` `}`   `}`

## Python3

 `# Python3 program to reduce the array` `# such that each element appears` `# at most 2 times` `from` `collections ``import` `Counter`   `# Function to remove duplicates` `def` `removeDuplicates(arr, n):` `    ``freq ``=` `Counter(arr)` `    `  `    ``# Taking empty list` `    ``l ``=` `[]` `    ``for` `i ``in` `range``(n):` `      `  `        ``if``(freq[arr[i]] >``=` `2``):` `          `  `            ``# Making frequency to 1` `            ``freq[arr[i]] ``=` `1` `            ``l.append(arr[i])` `            `  `        ``elif``(freq[arr[i]] ``=``=` `1``):` `            `  `            ``# Making frequency to 0 ` `            ``# and appending to list` `            ``l.append(arr[i])` `            ``freq[arr[i]] ``=` `0` `            `  `    ``# Printing the list` `    ``for` `i ``in` `l:` `        ``print``(i, end``=``" "``)`     `# Driver code` `if` `__name__ ``=``=` `"__main__"``:`   `    ``arr ``=` `[``1``, ``1``, ``1``, ``2``,` `           ``2``, ``2``, ``3``, ``3``,` `           ``3``, ``3``, ``3``, ``3``,` `           ``4``, ``5``]`   `    ``n ``=` `len``(arr)`   `    ``# Function call` `    ``removeDuplicates(arr, n)`   `# This code is contributed by vikkycirus`

## Javascript

 `function` `removeDuplicates(arr, n) {` `  ``// Create an object to store frequency of each element` `  ``const freqMap = {};`   `  ``// This array will contain the final elements from the input array` `  ``const temp = [];`   `  ``// Iterate over the input array to store frequency of each element` `  ``for` `(let i = 0; i < n; i++) {` `    ``freqMap[arr[i]] = (freqMap[arr[i]] || 0) + 1;` `  ``}`   `  ``// Iterate over the input array again to create a new array with unique elements` `  ``for` `(let i = 0; i < n; i++) {` `    ``// If an element is present more than once, take it once and set its frequency to 1` `    ``if` `(freqMap[arr[i]] >= 2) {` `      ``temp.push(arr[i]);` `      ``freqMap[arr[i]] = 1;` `    ``} ``else` `if` `(freqMap[arr[i]] === 1) {` `      ``// If an element is present only once, take it once and set its frequency to 0` `      ``temp.push(arr[i]);` `      ``freqMap[arr[i]] = 0;` `    ``}` `  ``}`   `  ``// Print the new array with unique elements` `  ``console.log(temp);` `}`   `// Example usage` `const arr = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5];` `removeDuplicates(arr, arr.length);`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `class` `Program` `{` `    ``static` `void` `RemoveDuplicates(``int``[] arr, ``int` `n)` `    ``{` `        ``// Dictionary to store frequency` `        ``Dictionary<``int``, ``int``> dict = ``new` `Dictionary<``int``, ``int``>();` `        `  `        ``// This list will contain the final elements from array` `        ``List<``int``> temp = ``new` `List<``int``>();`   `        ``// Iterate over array to store frequency of each element` `        ``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 an element is present 2 or more than 2 times, take it once and set` `            ``// its frequency to one, which means we have to take this element one time more` `            ``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)` `    ``{` `        ``// Array` `        ``int``[] arr = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5 };` `  `  `        ``// Size of array` `        ``int` `n = 14;`   `        ``// Function call` `        ``RemoveDuplicates(arr, n);` `    ``}` `}` `//This code is contributed by rudra1807raj`

Output

`1 1 2 2 3 3 4 5 `

Time complexity: O(N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up
Related Articles