OneCompiler

Implement a function called countUniqueValues, which accepts a sorted array, and counts the unique values in the array. There can be negative numbers in the array, but it will always be sorted.

225

multi pointer pattern   i  ↘  j


i

.

      j

Following is sample javascript code.

// multi pointer pattern

async function  countUniqElements(arrr)  {
  var arr = [...arrr]
  var left = 0;
  var right = 1;
  var uniqCount = 0;
  var unqArr = [];
  while(right < arr.length){

    if(arr[left] !== arr[right]) {
      left ++;

      uniqCount +=1;
      unqArr.push(left)
  
      
    }
    
    right ++;
    
  }
  //console.log(uniqCount, arr)
  return {uniqCount,unqArr };
}

input:

console.log(countUniqElements([1,1,1,2,3,4,5,6,8,8,9,9,10]))

output:

{
  uniqCount: 10,
  unqArr: [
    1, 2, 3, 4,  5,
    6, 7, 8, 9, 10
  ]
}

## Solution 2:

function countUniqueValues (arr1) {
   let arr = arr1.sort()
   let array = []
   for(var i=0; i< arr.length; i++) {
       if(arr[i] !== arr[i+1]) {
          array.push(arr[i])
       }
   }
   return array.length;
}

##  Solution 3:

function countUniqueValues(arr){
    if(arr.length === 0) return 0;
    let i = 0;
    for(var j=1; j<arr.length; j++) {
        if(arr[j] !== arr[i]) {
          i++;
          arr[i] = arr[j]
        }
    }    
    return i+1;  
}