I had lecture about this problem and as I understand, I have to find the lowest point from which this ball will break. I thought of using binary search to get O(logN) time complexity. If the ball breaks on the index and breaks again on the index – 1, we simply continue the search until we find an index where it breaks and the one to the left does not.
function two_crystals(data : boolean[]) : number {
let first_index = 0;
let last_index = data.length - 1;
while(first_index <= last_index){
let mid_index = Math.floor((last_index + first_index) / 2);
if (data[mid_index]) {
// Check if it doesn't break at the previous floor
if (mid_index === 0 || !data[mid_index - 1]) {
return mid_index;
}
// Continue searching in the lower half
last_index = mid_index - 1;
} else {
// Continue searching in the upper half
first_index = mid_index + 1;
}
}
return -1
}
Maybe I didn’t understand the problem correctly, but I think this option is better