DEV Community

Ashutosh Sarangi
Ashutosh Sarangi

Posted on

1 1 1 1 1

2 Crystal Ball Searching Problem Solved Using Javascript

2 Crystal ball problem find the 1st hit with minimum time complexity.

const arr = [false, false, false, false, true, true, true, true, true, true];

function two_crystal_balls(breaks) {
  const jmpAmount = Math.floor(Math.sqrt(breaks.length));

  let i = jmpAmount;
  for (; i < breaks.length; i += jmpAmount) {
    if (breaks[i]) {
      break;
    }
  }
  console.log(i, "i");

    const updatedPos = i - jmpAmount;

  for (let j = updatedPos; j<= i; j++) {
    if (arr[j]) {
        console.log('Answer ---> ', j);
        return ;
    }
}
  return -1;
}
two_crystal_balls(arr);

/*
Output
6 i
Answer --->  4 
*/
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

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

Okay