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;