ALT solution: -In this case, sorting is potentially costly but iwith built in sort ,it is O(log n). Also, by sorting we are easily able to find the max via last item in array so that saves time. Also, now we dont have to loop entire array when finding count. We just traverse backwards and exit soon as current element is less than max. function candle(arr) { let arrSorted = arr.sort((a, b) => a - b) let max = arr[arrSorted.length - 1] let count = 0 for (let i = arr.length - 1; i > 0; i--) { if (arr[i] < max) { break } count++ } return count }
@lime_crow2 жыл бұрын
thanks buddy, youve got my subscribe now.
@nikoo282 жыл бұрын
Thanks for the appreciation
@mrsmurf9112 жыл бұрын
Thanks man!!
@sasidharnaidu4507 Жыл бұрын
Maintain two variables max, count. We can do it in O(n) time in a single pass.
@tularamsa58143 жыл бұрын
awesome!!!!!!
@namansrivastava59553 жыл бұрын
I am thinking of a solution but not sure if i am thinking in the right direction. Can we sort the array and assign the last element to the max variable and count it's occurrence? By that we will have to traverse through the array just once.
@nikoo283 жыл бұрын
you can do that, but if you try to sort the array, that will increase your time complexity. Hence, the solution will end up taking more time
@namansrivastava59553 жыл бұрын
@@nikoo28 yeah, that make sense. I thought of one more, we can have a hash table with numbers as keys and there frequencies as values and find the max element also in the same run this will only take 1 iteration.
@nikoo283 жыл бұрын
Correct, but then you are taking extra space to store the hashtable. Always remember that as a good coding practice you should use the least amount of extra space and memory
@briana42892 жыл бұрын
@@nikoo28 You could sort using Java's built-in sort which would be less than O(n) complexity. Then if you iterate sequentially in reverse order you could have a worse case of O(n) but the common case would be far less, assuming all candle heights are not identical. Essentially you are counting the max values at the end of a list, and stop when the next value is less than the max.
@sasidharnaidu4507 Жыл бұрын
@@briana4289 how is sorting done in O(n) complexity? It's atleast O(nlogn), isn't it?
@hiteshgupta6502 жыл бұрын
Yes
@sergiu1sergiu2562 жыл бұрын
Cmone bro the worst tutorial i can't call the function in main class and i cant see how its working
@nikoo28052 жыл бұрын
Can you please give some detail about the problem you faced? The complete code is also available in the github link available in the description.
@nikoo28052 жыл бұрын
Do reply if you still face problems.
@amirakotbmassoud3172 Жыл бұрын
function birthdayCakeCandles($candles) { // Write your code here $height=0; $n=$candles[0]; for($i=1;$i$candles[$i]){ $height=$height+1; // $n=$candles[$i]; } } echo $height; } i made this but only on testcase 0 is right why?