Delete duplicates from sorted array (6.5) variant


I am struggling with the 2nd variant for 6.5 (EPI Java):

Write a program which takes as input a sorted array A of integers and a positive integer m, and updates A so that if x appears m times in A it appears exactly min(2,m) times in A.

I have adapted the original solution to keep track of the number of times an integer is repeated and I am trying to use this value to adjust writeIndex before writing the next non-repeated integer, but unable to figure it out.

Can someone please provide a hint?




Hi @ripuhan,

The hint I think is to having more variable(s) to store not only previous but also the one before previous elements. With that, you shall be able to adapt the original solution for this.



How I feel seeing unanswered variant questions on this forum:

Here’s my Javascript solution. Best wishes, future readers!

function removeDuplicates2(arr, m) {
  const min = Math.min(2, m);

  let vacancy = 0;
  let lastUniqueNum = null;
  let dupes = 0;

  for(let i = 0; i < arr.length; i++) {
    if(arr[i] !== lastUniqueNum) {
      if(dupes === m) {
        vacancy -= dupes - min;
      lastUniqueNum = arr[i];
      dupes = 0;

    arr[vacancy++] = arr[i];

  return vacancy;


This seems to work for me and it is written in python:

def delete_duplicates_min(A, m):
    if not A or m <= 0:
        return 0
    write_index = 1
    count = 1
    for i in range(1, len(A)):
        if A[write_index - 1] == A[i]:
            count += 1
            count = 1
        if A[write_index - 1] != A[i] or count <= min(2, m):
            A[write_index] = A[i]
            write_index += 1
    return write_index