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

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay