Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

am tried to make a program where the elements of an array will appear at most twice. Its working for some cases but also failing for some

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading