Practice › Hashing & Two Pointers
Remove Duplicates Allowing Two Copies
Medium · Hashing & Two Pointers · Asked at Meta, Amazon, Microsoft, Adobe
The array is sorted in non-decreasing order. Remove extra copies in place so that every value appears at most twice, keeping the order. Print the length k of the result on the first line and its elements on the second line.
Input
First line: n. Second line: n space-separated integers.
Output
First line: k. Second line: the first k elements after removal.
Constraints
- 1 ≤ n ≤ 10^5
- −10^4 ≤ a[i] ≤ 10^4
- the array is sorted
A write pointer k: copy a[i] to position k only if k < 2 or a[i] differs from a[k − 2] — the element two places back in the result.
Example 1
Input
6 1 1 1 2 2 3
Output
5 1 1 2 2 3
Example 2
Input
9 0 0 1 1 1 1 2 3 3
Output
7 0 0 1 1 2 3 3
Hints
- Use a write pointer k: the first k slots hold the answer so far.
- Because the array is sorted, a value may be written if it differs from the value two slots back in the answer.
Approach
For each element x: if k < 2 or x ≠ a[k − 2], write it to a[k] and increase k. If x equals a[k − 2], the answer already has two copies of x (they are adjacent in a sorted array), so skip it. Print k and the first k elements.
Complexity: O(n) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> a(n);
for (auto &x : a) cin >> x;
int k = 0;
for (int i = 0; i < n; i++)
if (k < 2 || a[i] != a[k - 2]) a[k++] = a[i];
cout << k << "\n";
for (int i = 0; i < k; i++) cout << a[i] << (i + 1 < k ? ' ' : '\n');
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n = data[0]
a = data[1 : 1 + n]
k = 0
for x in a:
if k < 2 or x != a[k - 2]:
a[k] = x
k += 1
print(k)
print(*a[:k])Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
int[] a = new int[n];
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (int) in.nval;
}
int k = 0;
for (int i = 0; i < n; i++)
if (k < 2 || a[i] != a[k - 2]) a[k++] = a[i];
StringBuilder sb = new StringBuilder();
sb.append(k).append('\n');
for (int i = 0; i < k; i++) sb.append(a[i]).append(i + 1 < k ? " " : "\n");
System.out.print(sb);
}
}Solve Remove Duplicates Allowing Two Copies online · All practice problems