DEV Community

Dumb Down Demistifying Dev
Dumb Down Demistifying Dev

Posted on

4 4

Unique Values Counter

Implement a function CountUniqueValues, which takes in a sorted Array of positive and negative integers.
It should count and return the number of unique values in the Array.

Thoughts:

  • This is an easy question.
  • It should be easily checked against using JavaScript.
  • It should try to use pointers to track the position of values to be compared against.
  • No need to mutate the original Array.
function CountUniqueValues(arr) {
    if (arr.length === 0) return 0;

    let uniqueValueIndex = 0;
    let counter = 1;

    for (let i = 1; i < arr.length; i++) {
        if (arr[i] !== arr[uniqueValueIndex]) {
            counter++;
            uniqueValueIndex = i;
        }
    }

    return counter;
}

// sample data
const sorted_array = [-10,-11,1,1,1,2,3,4,5,5,5,6,7,7,7,7,8];
// result
console.warn(CountUniqueValues(sorted_array));
// to be asserted against result
console.warn(Array.from(new Set(sorted_array)).length);
Enter fullscreen mode Exit fullscreen mode

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)