Home > OS >  am tried to make a program where the elements of an array will appear at most twice. Its working for
am tried to make a program where the elements of an array will appear at most twice. Its working for

Time:12-21

I tried to make a program where the elements of an array would appear at most twice. Its working for some cases but also failing for some. I'm trying to figure out the mistake in the logic. The two-pointer approach is being used to solve the question.

the code I tried is

const fun=(nums,n)=>{
 let arr=[]
    let left=0;
    let counter=0
    for(let i=1;i<n;i  )
    {
        if(nums[left]<=nums[i]&&counter<=1)
    {
        counter  ;
        left  
        arr.push(nums[i])
    }
    counter=0
    }
return arr
}

input =[2 2 2 3 4 4 9],7

CodePudding user response:

You don't need two pointers for this if the array is sorted. You can simply keep track of the current number and its frequency.

const fun=(nums,n)=>{
  let res = [];
  let prev, freq;
  for (const num of nums) {
    if (num != prev) prev = num, freq = 1;
    else   freq;
    if (freq <= 2) res.push(num);
  }
  return res;
}
console.log(fun([2, 2, 2, 3, 4, 4, 9],7));

  • Related