skip to Main Content

I recently came across one problem statement, The initial function was given to me with two parameters and I have write the body part. I tried to solve it and wrote some code that was working fine. However, I still couldn’t figure out what was the use of first parameter.

Here is my solution

function findUniqueValidNumbers(N, arr) {
  const uniqueNums = new Set();
  const prevIndexes = {};
  
  for (let i = 0; i < arr.length; i++) {
    const num = arr[i];
      if (!prevIndexes.hasOwnProperty(num)) {
        // If this is the first occurrence of the number, add it to the uniqueNums set
        uniqueNums.add(num);
        prevIndexes[num] = i;
      } else if (prevIndexes[num] % num === 0) {
        // If this is not the first occurrence of the number, but the index is divisible
        // by the previous occurrence index, we can add it to the uniqueNums set
        uniqueNums.add(num);
        prevIndexes[num] = i;
      } else {
        // If the index is not divisible by the previous occurrence index, we can remove
        // the number from the uniqueNums set (if it was previously added)
        uniqueNums.delete(num);
      }
  }
  
  return uniqueNums.size;
}

findUniqueValidNumbers(5, [1, 2, 1, 2, 2]) // output 1

findUniqueValidNumbers(3, [1, 2, 3]) // output 3

Problem statement

enter image description here

2

Answers


  1. If you wanted, you could substitute that first parameter in place of arr.length.

    for (let i = 0; i < N; i++) {
    

    But your

    for (let i = 0; i < arr.length; i++) {
    

    could well make more sense to you at a glance while reading the code.

    The first parameter isn’t necessary or that useful, it simply happens to be part of the problem description that you can decide to use (or not, and work around).

    This is a common feature of coding test problems.

    Login or Signup to reply.
  2. Just for fun, a one-liner using array functions:

    function findUniqueValidNumbers(arr) {
      return Object.entries(arr.reduce((a,e,i)=>((a[e]??=[]).push(i+1),a),{}))
        .filter(([,a])=>a.every((e,i,r)=>i===0 || e%r[i-1]===0)).length;
    }
    
    console.log(findUniqueValidNumbers([1, 2, 3]))
    console.log(findUniqueValidNumbers([1, 2, 1, 2, 2]))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search