# Birthday Cake Candles

# Birthday Cake Candles

apghr + 25 comments A compact C++ solution:

#include <iostream> int main(){ int c, n, max = 0; std::cin.ignore(); while(std::cin >> n) max < n ? c = !!(max = n) : c += max == n; std::cout << c; return 0; }

v1nea + 1 comment Like this a lot. Thanks.

mohammedavez85 + 3 comments `c

# include

# include

# include

# include

# include

# include

# include

int birthdayCakeCandles(int n, int ar_size, int* ar) { // Complete this function int i,j,temp,count=0,b; for(i=0;i

`b=ar[0]; for(i=0;i<n;i++){ if(b == ar[i]){ count++; } }`

return count; }

int main() { int n,ar_i; scanf("%i", &n); int *ar = malloc(sizeof(int) * n); for(ar_i = 0; ar_i < n; ar_i++){ scanf("%i",&ar[ar_i]); } int result = birthdayCakeCandles(n, n, ar); printf("%d\n", result); return 0; } BRO THIS CODE SAYS TIME LIMIT EXCEEDED PLEASE HELP

Yakubk_98 + 6 comments use c++ and you'll be fine

int birthdayCakeCandles(int n, vector <int> ar) { // Complete this function int max = ar[0]; int count = 0; for(int i=0; i<n; i++) if(ar[i] > max) max = ar[i]; for(int i = 0; i < n; i++) if (ar[i] == max) count++; return count; }

sandeepkataria + 5 comments this code was working on some test case but not all please help me

vaishaligarg2012 + 8 comments /*You should do like this... */

int max=ar[0]; int count=0; for(int i=0;i<n;i++){ if(ar[i]>max){ max=ar[i]; } } for(int i=0;i<n;i++){ if(ar[i]==max){ count++; } } return count;

jdanielys07 + 1 comment In java, maybe this way can help you! :)

if(ar!=null && ar.length>0 && n>0) { int maxHeight=0, numMaxHeight=1; for(int i=0; i<ar.length; i++) { if(maxHeight<ar[i]) { maxHeight=ar[i]; numMaxHeight=1; }else if(maxHeight==ar[i]) { numMaxHeight++; } } return numMaxHeight; } return 0;

Stelios10 + 3 comments just an optimization, even though in this case your code is fine: if you try an array with negatives, then you ll never get inside your if-statements. so the numMaxHeight will never change, so you dont really compute it in such cases. so this solution for an array with negatives, where the max negative appears more than once, will fail. eg [-1, -1]

proposed solution: set numMaxHeight = 0 on initialization

shashank_sm + 0 comments [deleted]sirmaridvan + 1 comment Can a birthday cake candle have a negative length?

Zachurnia_Tate + 1 comment No, candles cannot have a negative length buddy. I don't kniw what kind of world your living buddy.

salvgal + 1 comment Buddy, even though your real world experience gives you a meaning to things, you have to cover up your code from all the edge cases: you never know what kind of input your function take, especially if the problem description does not specify that the input array contains positive integers only, and a negative ints array is a valid input for our function

atineo + 0 comments You are correct that you have to proof safe your code but the mandate is telling you what input you are getting. Positive integer arrays. Refer to the constraints section of the explanation.

szatmary_zoltan1 + 0 comments But you shouldn't do anything like int max = 0 (except if there are no negative numbers or if it's indicating the index of the maximum value). Instead you should use: int max = ar[0];

shrikanth_n23 + 0 comments You can simplify it like this:

int max=ar[0]; int count=0; for(int i=0;imax){ max=ar[i]; count = 1; //Reinitialize count if you found a new max }

`else if(ar[i]==max){ count++; }`

} return count;

I this case you are traversing the vector only once.

pkarif4249816 + 0 comments [deleted]pkarif4249816 + 0 comments [deleted]soumabratabhatt1 + 0 comments i did the same thing.But it is showing me 4 test cases failed.

osama_abusitta + 0 comments int max=ar[0]; this wrang staement , replace with int max= 0

RizviTammar + 0 comments exactly same i did but it give me error of indexoutofbound exception an can't resolve it" :( what to do?

sandhyarani_dot1 + 0 comments [deleted]

jord_fumar + 4 comments Be aware of time complexity. In my testcase 4, n was 10000. If you use a sorting algorithm with n^2, you will get a runtime error.

The way I structured my code is:

- Sort the array from min to max (quickSort)
- Parse from the very end of the array and iterate count++.
- When your values are no longer identical, stop.

jagmeetsingh + 6 comments I tried this

static int birthdayCakeCandles(int[] a) { Arrays.sort(a); //double pivot QuicKSort int count = 0; int i = a.length - 1; int tallest = a[i]; while (a[i--] == tallest) { count++; } return count; }

It is failing the test case

100000 followed by 100000 times 9999999 (as height of candles(array values)).

x_ireesh_x + 0 comments Pass all Testcases..

`static int birthdayCakeCandles(int[] ar) { Arrays.sort(ar); int result = 1; int decriment = 2; while((decriment <= ar.length) && (ar[ar.length-1] == ar[ar.length-decriment])){ result++; decriment++; } return result; }`

rishavtandon93 + 1 comment Try This

static int birthdayCakeCandles(int[] ar) {

`int count =0; Arrays.sort(ar); int maxHeight = ar[(ar.length)-1]; for(int i=0;i<ar.length;i++) { if(ar[i]==maxHeight) { count++; } } return count; }`

Kanahaiya + 2 comments Hi,

Your solution is good but it will take O(nlogn) time due to sorting which can be optimized to O(n)

Here is the video explanation of my solution in O(n) time -

Any comments and feedback will be appreciated.

wdodman + 1 comment Thanks for that. I worked out a solution where I do it in O(n) time. Posted on your video.

Kanahaiya + 0 comments most welcome. :)

If you dont mind can you please provide a feedback on my video by commenting or liking & disliking. It will help me and others too to find the solution over internet.

munnidivya93 + 2 comments thanks

Amit_Sharma + 0 comments need to add one more check in while condition for all the array elements with same value

while ( i > -1 && a[i--] == tallest ) { count++; }

dpkcareergreatn1 + 0 comments Count should be initialized to 1 as there is atleast one tallest. In this case, if the frequency of largest element is 0, count would return 0 which is an error

harikrishnaprak1 + 0 comments while (

**i>-1**&&a[i--] == tallest) { count++; }You just forgot to check whether the index i is within the bounds.

bertgayus + 0 comments if you use quicksort u already have O(nlogn) which is worse than just iteratring through the array and saving the highest value and then just iterate a second time incrementing a counter everytime the value is similar to the saaved one. then complexity is O(2n) = O(n). With n = 100 you would have ~ 600 steps(n*logn = 100 * 6 = 600) with your solution and just 200 steps with mine

matthew_zilkie + 0 comments `Did you try using c++ std::sort(ar.begin(), ar.end()); ? I did and it worked flawlessly. int birthdayCakeCandles(int n, vector<int> ar) { // Complete this function sort(ar.begin(), ar.end()); int max = ar[ar.size() -1]; int count = 0; for(auto num : ar) { if(num == max) ++count; } return count;`

}

anudeepvattikon2 + 0 comments Thanks a lot!!.I was just wondering where did i go wrong..Thanks a lot again

luckysam09 + 0 comments ar[i]-max==0 in second if worked for me

generalom1234 + 0 comments sandeep did u use unsigned long or any other data type which allows you to take in large amounts of data?

akshaythear + 0 comments This code is assuming that first entered element is always the largest one.So it wont work in some cases... in short it is a wrong code.

r_umans + 1 comment Since height of the candle is always at least 1, you can safely assume max = 0; Then loop all at once, you dont need a double loop. (Java syntax)

If(max < ar[i] ) { max = ar[i]; count =1; } else if (max==ar[i]) count++;

x_ireesh_x + 1 comment [deleted]x_ireesh_x + 1 comment [deleted]x_ireesh_x + 0 comments [deleted]

Anoop_SS + 0 comments You don't need the second loop. Checking of equal can be done in the else of

`if(ar[i] > max)`

matthew_zilkie + 0 comments [deleted]mercia_a + 0 comments thank you!

shahzadhafeez63 + 1 comment instead of using two loops, we can solve it in one loop. static int birthdayCakeCandles(int[] ar) {

`int size = ar.length, max = Integer.MIN_VALUE ,count = 0; //find tallest candle and count for (int i=0;i<size; i++) { if (ar[i]>max) { max = ar[i]; count = 1; } else if (ar[i]==max) { count++; } } return count; }`

harikrishnaprak1 + 0 comments Nice!

josephawilson86 + 1 comment Ask yourself a few questions:

- What do I need to return?

-The number of highest candles

- How would I get that number?

-I need to know what the highest candle is.

-I need to know how many of them there are.

- How would I know which is the highest candle?

-Simple comparison should work for knowing what the highest is. Just store it in a var and reset when I find one that's bigger.

- How would I track how many of they there are?

-Store the quantity in a var, increment it whenever I find one of the Highest candles and reset it each time I find a new highest candle.

salvgal + 0 comments Thank you Joseph, your explanation of the problem brouhgt me to this simple solution that run in O(n):

`int ret = 0; int max = 0; for(int a : ar){ if(a > max){ ret = 1; max=a; } else if(a == max) ret++; } return ret;`

Sometimes the hardest part of these problems is finding what the question is asking more than how to solve it.

wdodman + 0 comments ar.sort(); ar.reverse(); let m = 0; let k = ar[0]; while (parseInt(ar[m]) === parseInt(k)){ m++; } return m; }

passes 8 of 9.

qu4ku + 0 comments i'm not into c++, but this looks savage :)

trungskigoldberg + 1 comment Can you explain more about the complicated, savage version of that ternery statement? I really want to know this nifty code!

apghr + 15 comments while(std::cin >> n) max < n ? c = !!(max = n) : c += max == n;

can be translated as:

while(std::cin >> n){ // for each candle n check: if(max < n) { // does n set a new record in height? max = n; // if that's so, then n is the new max height c = 1; // and the counter c must be set to 1 again. "!!" is a cheap trick to convert any value different from 0 into 1 } else { // otherwise check if the new candle is as tall as max if (max == n) c++; // in that case, add 1 to counter (otherwise add 0) } }

arpita414 + 0 comments Too good

oswald200801 + 0 comments Nice one !!

aishwarya217 + 0 comments Good!

adityabcs93 + 0 comments nice one

lehieuminh231 + 0 comments nice. thank you

tarsum + 0 comments Well I came up with similar algorithm, so thumbs up. Also seems like solution in editorial goes though array twice, and this goes only once.

Vishwas92 + 0 comments hats off..

ichidan + 2 comments Nice one. I arrived at same algo in C, minus the one liner ternary. Looks neat, I like it. Although I'd be curious if there is not a small performance loss of doing:

c = !!(expr);

vs

(expr); c = 1;

the former may require additional conditional logic depending on architecture (for instance x86 - http://riffwiki.com/MOV_(x86_instruction) - the MOV instruction doesn't affect ZeroFlag, so I'd guess CPU would have to evaluate whether your expr results in a non-zero value. It's obvious to us as we can see the wider context of the algorithm, but not the CPU)

kurian_benoy + 0 comments thanks

viigihabe + 0 comments It is not CPU that analyses your c++, the compiler does. CPU doesn't "thin" but compiler does. It is really pointless to "optimize" your code this way because compiler is required to emit assembly that does what is ment but in which order and through which instructions, it is not specified. You better belive it does good job. You express c++ although it is slower than ++c: there is no way the compiler would use slower version if it doesn't afect the program flow. With no optimization flags may be.

lakshay91dutt + 0 comments [deleted]rahulsahu_blog + 0 comments This is brilliant!

gharibakhamis + 0 comments nice why didn't i think of this sooner

parvpareek + 0 comments TYSM!! Helped me a lot..

sabahat_usman_su + 0 comments I did the same thing but my code fails for some tests :O

jagmeetsingh + 0 comments I tried same in java. It worked! Thanks (:

int temp, max = 0, result = 0, n; for (int i = 0; i < arCount; i++) { n = scanner.nextInt(); temp = (max < n) ? (result = ((max = n) >= 0) ? 1 : 1) : (result += (n == max) ? 1 : 0); }

Ray1984 + 0 comments Very nice -- thanks for nudging me to think about it as a streaming algorithm :-)

colonel_bishop + 0 comments It's cool! Thanks!

ScienceD + 1 comment I dont understand how cin.ignore(); works... And how you can feed input into loop condition...

thermosphere453 + 0 comments cin.ignore() ignores the input of number of candles as its not needed in his algorithm and the input in loop works as long as the input isnt 0 or null, while loop works for any number in the test condition.

kachi_kinjal + 1 comment can u give the solution for c programming.

oswald200801 + 0 comments int main(){ int n; scanf("%d",&n); int *height = malloc(sizeof(int) * n); int max=height[0]; int count=0; for(int height_i = 0; height_i < n; height_i++){ scanf("%d",&height[height_i]); } for(int i=1; imax){ max=height[i]; } } for(int k=0; k

unicpawan + 8 comments can u please tell me why this code is not able to pass all the test case

// the code goes here..

int main(){ int n,i,max=0,frequency=0;

int

*ar =(int*) malloc(sizeof(int) * n);`scanf("%d", &n); for( i = 0; i < n; i++){ scanf("%d",&ar[i]); } for(i=0;i<n;i++){ if(ar[i]>max){ max=ar[i]; frequency=1; } else if(ar[i]==max){ frequency++; } } printf("%d",frequency); return 0;`

}

bharat_reddy18 + 0 comments # include

# include

# include

# include

# include

# include

# include

int birthdayCakeCandles(int n,int a[]) { long long int i,max=0,d=0; for(i=0;imax) { d=1; max=a[i]; } else if(a[i]==max) { d++; } } return d;

}

int main() { int n; scanf("%i", &n); int *ar = malloc(sizeof(int) * n); for(int ar_i = 0; ar_i < n; ar_i++){ scanf("%i",&ar[ar_i]); } int result = birthdayCakeCandles(n,ar); printf("%d\n", result); return 0; }

kuppesh_ds + 0 comments Return frequency to calling function instead of printig here.

vishalgwalani6 + 0 comments if you have case like 20,40,90,90,90 so you see according to your code in max variable value will 20 and frequency will be 1 and after the loop ends your result will be 4 instead it should be 3

shac_bandagi + 0 comments your else if part should be in for loop and in if statement remove that frequency set otherwise max number counted twice.

anurag0430 + 0 comments your are returning count of candles of same height. We have to return the number of candle he/she can blow out.

gaurav_877 + 0 comments you havent calculated the final max value and processed it before hand for comparision

maheshmnj + 0 comments what is max before entering the for loop??

gjaiswal108 + 0 comments because you have allocated memory to pointer ar using malloc function before taking the value of n from user. you should first take input n from user and then allocate memory to the pointer, i.e. first use scanf("%d",&n); then write int

*ar=(int*)malloc(sizeof(int)*n);hope, you understand.

kmschaal902 + 0 comments compact indeed, great job!

andrew_hedy77 + 4 comments Yeah, yours is way cleaner than mine

int birthdayCakeCandles(int n, vector <int> ar) { int count = 1; sort(ar.begin(), ar.end()); reverse(ar.begin(), ar.end()); for (int i = 0; i < n; i++){ if (ar[i] == ar[i+1]){ count++; } else break; } return count; }

amitsoni90 + 0 comments Why we need vector here?

cse_115 + 0 comments good solution

wem18 + 1 comment Solid solution. Wouldn't it be more efficient to do a for loop such as

//call sort //set int max = ar[n] for(int i = n; i>0; i++) { if(ar[i]==max) { count++; } else{ break; } return count; }

So you can avoid calling both sort and reverse? Not trying to correct you, genuine question

abhi69sindh + 0 comments it will not pass all the testcases

3001pratap + 0 comments [deleted]

shantanu_knight + 0 comments Great one

karthikeyan90422 + 0 comments What is the use of cin.ignore() please tell me

lyj1186669164 + 0 comments That's so nice.Thanks

VIDYARANIGIDDE + 0 comments what is the role of cin.ignore() ?? what if we do not write that line?

cu_16bcs2416 + 0 comments wao! stupendous code!

benaffleks + 1 comment Can someone explain to me :

max < n ? c = !!(max = n) : c += max == n;

nvinson234 + 0 comments C++ allows for integers to be treated as logical values. If the integer is non-zero, it's "true" and if the integer is zero it's "false". The

`!`

is the logical-not operator and the language standard says`!0`

will be equal to 1.A similar rule holds for

`max == n`

. Whenever, that expression evaluates to "true" it will also represent the numerical value 1.Assignments, such as

`max = n`

, also have the side-effect of "returning" the assigned value (n in this case).Therefore, this is a really terse way of writing:

if (max < n) { max = n; c = 1; } else if (max == n) { c += 1; }

breakbadsp + 9 comments bro use python3 :

def birthdayCakeCandles(ar): return ar.count(max(ar))

No looping, no veriables, no mess

nsuniln1 + 0 comments [deleted]overwhelm + 0 comments wow this is crazy, thank you

lampladam1 + 0 comments i did the same. python is so useful when it comes to counting the number of occurences

dondorian + 0 comments No looping?

So, how were "max" and "count" calculated?

aida71 + 1 comment This is wrong if you do an interview. They most likely want to see a solution which is O(n) and yours is O(n^2).

This is mine, which is O(n):

def birthdayCakeCandles(ar): max_h = ar[0] max_n = 1 for c in ar[1:]: if c > max_h: max_h = c max_n = 1 elif c == max_h: max_n += 1 print(max_n)

georgechristied1 + 0 comments cheers for pointing this out, but is the solution provided by breakbadsp actually O(2^n)?

samarththeengin1 + 0 comments U are great bro.

vtrivenirao + 0 comments so simple !!!!

gleventis94 + 0 comments [deleted]marcomereu2015 + 0 comments Thank you!

ilya_zarembsky + 0 comments Cute

Kanahaiya + 0 comments ## 100 % working code with video explanation -- All Test Case Passed..!!

## Here is the video explanation of my solution -

and you can find most of the hackerrank solutions with video explaination here-

https://github.com/Java-aid/Hackerrank-Solutions

and many more needs to be addeed.

Regards,

Kanahaiya Gupta

Git Hub URL | https://github.com/Java-aid/

LIKE US | https://www.facebook.com/javaaid/

SUBSCRIBE US | https://www.youtube.com/c/JavaAidTutorials

TELEGRAM LINK| http://t.me/javaaid

gadarsh555 + 1 comment can you explain it's process of working ?

Kanahaiya + 0 comments You can go through this tutorial-

Here is the video explanation of my solution -

shubhambajare + 1 comment thanks a lot !! This helps me to fingure out the problem. :)

Kanahaiya + 0 comments most welcome. :)

If you dont mind can you please provide a feedback on my video by commenting or liking & disliking. It will help me and others too to find the solution over internet.

Do not forget to subscribe my youtube channel for hackerrank solutions .:)

ali75 + 0 comments one line code C++:

return count(ar.begin(), ar.end(), *std::max_element(ar.begin(), ar.end()));

umangsomtiya8083 + 1 comment BRO THIS CODE SAYS TIME LIMIT EXCEEDED PLEASE HELp

Kanahaiya + 1 comment Hi,

your solution may be correct but may not be efficient .you can optimized your solution further.

Here is the video explanation of my solution in O(n) time -

https://www.youtube.com/watch?v=1gxFE9EfanE&list=PLSIpQf0NbcCltzNFrOJkQ4J4AAjW3TSmA

I would really appreciate your comments and feedback on my video.

umangsomtiya8083 + 1 comment thankyou very much sir

Kanahaiya + 0 comments most welcome. it would be great if you can please provide your comments, like, dislike on my video how i did it..It motivates me to create better content for my audience.

karan316 + 0 comments How is this code working even when the numbers are very big numbers?

ryanfehr18 + 14 comments A small Java solution in O(n) time with O(1) space:

//Java 8 /* Initial Thoughts: We can keep a running max and update it if we find something larger, if we find something smaller we just keep looking and if we find something equal then we increment a counter variable Time Complexity: O(n) //We must check the height of every candle Space Complexity: O(1) //We only store a max and a frequency */ import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int tallest = 0; int frequency = 0; for(int i=0; i < n; i++){ int height = in.nextInt(); if(height > tallest){ tallest = height; frequency = 1; } else if(height == tallest) frequency++; } System.out.println(frequency); } }

You can find more HackerRank solutions like this here

Dsmeenakshi + 1 comment if height is less than tallest means...wat wil happen

ryanfehr18 + 1 comment As mentioned above:

/* if we find something smaller we just keep looking */

Basically, we don't care about candles < tallest

Dsmeenakshi + 0 comments thank you dude

wyrlvillazorda + 0 comments it's great..thank you!

randy_evered + 1 comment `int max = 0; for (int v : a) if (v > max) max = v; int count = 0; for (int v : a) if (v >= max) count++; return count;`

sntz1 + 1 comment you can avoid doing two for loops by doing something along the lines of:

int max = 0; int count = 0; for (int v : a) { if (v > max) {max = v; count = 1;} else if (v == max) count++; } return count;

You can avoid iterating over the collection twice

srijanPaul + 0 comments ah yes, that's pretty smart.

SupreethMC + 0 comments Nice approch !

borisaltynnik + 3 comments Why not to use first array element like initial value of max ? Does it make any sense ?

static int birthdayCakeCandles(int n, int[] ar) { int max=ar[0]; int num=1; for (int i=1;i<n;i++){ if (ar[i]>max){ max=ar[i]; num=1; } else if (ar[i]==max) num++; } return num; }

iamkarthik49 + 0 comments Yeah ! I did the same thing but complicated it... Your's looks clean and clear thanks for the solution... :) .

santunu23 + 1 comment Nice one thanks for sharing,actually I have been working on this solution for a hour,finaly it work thanks dude.

Coder_Zuki + 0 comments No Probs Dude

renton284 + 1 comment This is not works, when a number in the array (last number of array) is bigger than then previous ones the result is not ok.

oliver_erhart + 0 comments The result would be 1 (correct). Because of the "else if" it doesn't get incremented again.

kvnfrederiksen0 + 0 comments HAH! I did the exact same thing. Nice.

int n = in.nextInt(); int j = 0; int max = 0; for(int i = 0; i < n; i++){ int x = in.nextInt(); if(x > max){ j = 1; max = x; } else if(x == max) j++; } System.out.print(j);

shantanu_bugadi + 0 comments simply wow.. what i got by this code is , try to do most of it simultaneously....

3001pratap + 1 comment static int birthdayCakeCandles(int n, int[] ar) { int count=0; Arrays.sort(ar); int tallest = ar[n-1]; for(int i=0; i<n; i++) { if(ar[i] == tallest) count++; } return count; }

fhrazib + 0 comments I think this can be improved a little bit using a break. We don't need to traverse all the array to get the total count when the array is sorted (here in ascending order) -

`Arrays.sort(a); int tallestOne = a[n-1]; int count = 1; for(int i=n-2; i>=0; i--){ if(a[i]==tallestOne) { count++; } else break; }`

hollybush + 0 comments Amazing solution mate!

zakiralig184 + 0 comments Cool!

pep1439 + 0 comments use

tallest = Integer.MIN_VALUE

instead, for general use.

stephen_kalletta + 0 comments very clean. I was sorting it and grabbing the last values, but I like this much better. thanks for sharing

Coder_Zuki + 2 comments Did This...! Seems Simple right?

static int birthdayCakeCandles(int n, int[] ar) { // Complete this function int size=ar.length; int tall=ar[0]; int count=0;

`for(int i=0 ; i<size ; i++) { if(ar[i]>tall) { tall=ar[i]; } } for(int j=0;j<size;j++) { if(ar[j]==tall) count++; } return count; }`

j_zambre66 + 0 comments [deleted]nikhilgarakapat1 + 0 comments Give count=1;

j_zambre66 + 0 comments Can be done it like this.

int max = 0, count = 1; for (int v : ar) { if (v == max) count++; if (v > max) max = v; } return count;

ATVex + 10 comments Counting the tallest candles.

n = int(input().strip()) height = [int(height_temp) for height_temp in input().strip().split(' ')] print(height.count(max(height)))

abhishek106 + 1 comment python is the best!

rudra_utpal + 1 comment Any problem with Java @abhishek106

import java.util.*; public class Solution { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); ArrayList<Integer> al=new ArrayList<Integer>(); for(int i=0;i<n;i++) al.add(scan.nextInt()); System.out.println(Collections.frequency(al,Collections.max(al,null))); } }

aaron_gomez1 + 1 comment While this works, you loop through the complete collection of values 3 times. First while reading it in the scanner. Second while scanning for the max value in the collection after reading it in and third to count the number of times it was found.

fernando_becerr1 + 1 comment anyway the time complexity is O(n+n+n) = O(n)

riaan_rvr + 1 comment I'm not too familiar with the BigO notation, so an honest question how does it become n+n+n shouldn't it be 3n rather as you are doing full loops over all elements?

hua_duy + 0 comments In BigOh notation, I believe they drop the constants in front of n because exponents matter so much more that the constants are negligible.

egrodo1 + 0 comments [deleted]egrodo1 + 4 comments Why do that instead of just?

n = int(raw_input().strip()) candles = map(int,raw_input().strip().split(' ')) print candles.count(max(candles))

randy_evered + 1 comment Wow, egrodo1, Python for the win!

zimmah + 0 comments javascript is just this:

const birthdayCakeCandles = a => (f => a.filter(v => v === f).length)(Math.max(...a));

Javascript isn't as hard as you think, you just need to understand it.

Modelmat + 0 comments I basically did the same thing!

pheepia7788 + 0 comments nice code! as I am a beginner, I think very long and messy code.... lol

GodsonLG + 0 comments Map object doesn't have the count attribute. You will get an error

Dulguun_Otgon + 0 comments [deleted]helderIO + 0 comments [deleted]dandaraviteja + 2 comments n = int(input().strip()) ar = (list(map(int, input().strip().split(' ')))) print(ar.count(max(ar)))

paccel22 + 0 comments Thank you! I hadn't realized Python had a count method for lists that basically reduces the problem to 1 step.

Anubhav_singh + 1 comment what is the code of "count" function?? bcos when I am using loop instead of count fuction, its taking too much time to run. pls help??

ARXINO + 1 comment I am using loop but it is the same thing with ar.count(max(ar))

def birthdayCakeCandles(n, ar): max_height=0 double=0 for x in range(n): if ar[x]>max_height: max_height=ar[x] for y in range(n): if ar[y] == max_height: double+=1 return double

Shaurya_at_HR + 0 comments Thanks Arxino sir but after I started to run the code it showed a runtime error. I was asking that this function has 2 parameters but when below when the function is called it has only 1 parameter(ar). So what shall I do. Actually I am 13 years old and a beginner for coding in python. Pls help..

sehan2 + 4 comments from collections import * def birthdayCakeCandles(n, ar): res = Counter(ar) return res.most_common()[0][1]

croqaz + 0 comments Exactly like I did! Nice!

rowlandoti + 1 comment This is not a correct solution but I do not know why it is passing. You should:

- Get the max element
- Return or print its count/frequency.

pWiszniewski + 0 comments In some test cases, the highest (max) element is the one most common - like in example case, where 3 is the most common element. It also passes some test cases. The correct solution is the one with Counter.

vinasatinfo + 0 comments just simple

`return Counter(ar).most_common()[0][1]`

actually :-)

megha_sharma3333 + 0 comments Why is there a [0][1]?

Spiznak + 2 comments My solution finishd in about half the time, I would assume because I'm looping through it only once. Depends on whether you want a quick and dirty solution (mine) or one that's more Pythonic (in your case, can be more difficult to read):

n = input() arr = input().split() theMax, count = 0, 0 for x in arr: x = int(x) if x > theMax: theMax = x count = 1 elif x == theMax: count += 1 print(count)

icehongssii + 0 comments data=[10,3,333,333,333,0,13] tmp=data[0] #max data tmp2=0 #max data counter for i in range(len(data)-1): for j in range(i+1,len(data)): if(tmp<=data[j]): tmp=data[j] for k in range(len(data)): if(data[k]==tmp): tmp2+=1 print(tmp2)

this was my code. to get max_height, i use the loop twice. so it didn't work. but like you said, its working with single loop! thanks and it is so amazing that you used single looop... never imagined it

gb3010 + 0 comments I use max function in list. 7 out of 8 test cases work. I am not sure what's wrong with my code. Can you please have a look ?

n1=input().strip() # Input age value b1=input().strip().split() # Input list of candle heights def birthdayCakeCandles(n,b): c=0 z=max(b) for i in b: if i == z: c += 1 return(c) y=birthdayCakeCandles(n1,b1) print(y)

nicolasmontoya + 2 comments similar:

input() arr = list(map(int, input().split())) print(arr.count(max(arr)))

pWiszniewski + 1 comment EDIT: My mistake, i've missread the description :(. So the rest of the comment is invalid.

This doesn't work. It only counts how many times the highest element from the list (max(arr)) is in the list. In some test cases it works. In some it doesn't -> it's not a correct solution

brevnovak + 1 comment i don't understand. it's what we are looking for, is it not?? ;)

pWiszniewski + 0 comments You're right, I've missread the description.

wanwanzhang + 1 comment Hi I also use the same way to count in Python print(arr.count(max(arr))), but the result is always 2, none, which show me the worng answer. I do not know why it show me (2, none) instead of just 2.

sairajee + 0 comments Try to return the value from the function instead of printing.

return(ar.count(max(ar)))

EeXoR_Daniel_Ng + 0 comments python FTW:>

disabajn + 4 comments Python:

return ar.count(max(ar))

hongsy + 0 comments # YES.

#alltheothersolutionssuck

tom_wagner + 0 comments so good!!

antagonistpotato + 0 comments Sad to think I have discovered a one-liner just to see the discuissions and run into it here, but well, it happens

zimmah + 0 comments Ok, now THAT is short.

jeffmagill + 2 comments C# solution...

int tallest = height.Max(); int count = height.Count(c => c == tallest); Console.WriteLine(count);

indyHarcourt + 3 comments Or

int result = ar.Where(i => i == ar.Max()).Count();

unSatisfied + 0 comments That's O(n^2) since you're finding the max value on each iteration of the where statement. The best solution would be to use a single for/foreach loop, but jeffmagill's solution (looping through the list twice) is still much more efficient than this.

shatrudhankr + 1 comment [deleted]laysa_uchoa + 0 comments best comment

daeden + 0 comments I don't think you deserver a downvote, its solution i came up with the returned failed tests (tests timed out) for me.

I wish it was explained where other than comments why this wasn't a valid result.

leonardomiceli87 + 0 comments C# other way

var max = ar.Max(); return Array.FindAll(ar, s => s == max).Length;

Dalenguyen + 8 comments Nice to have modern JavaScript:

function birthdayCakeCandles(n, ar) { // Complete this function var max = Math.max(...ar); var result = ar.filter(c => c === max); return result.length; }

andrewseaton + 0 comments nice. I looped through the array to count occurances of "max". Using filter makes it so much simpler.

aJaxs + 0 comments è¿™ä¸ªfilterå¾ˆæœºæ™º

sameer_jain1 + 0 comments Exactly what I am thinking, but not sure why this question appearnign wrong at the moment, it doesnt have all the parameters so its throwing error to me

netris + 0 comments [deleted]netris + 3 comments You could even do this in a single line of code, like so:

`function birthdayCakeCandles(ar) {`

return ar.filter(i => i === Math.max(...ar)).length;

}But I found that this causes recursion issues. This works perfectly fine though:

`function birthdayCakeCandles(ar) {`

var max = Math.max(...ar);

return ar.filter(i => i === max).length;

}brecht_pynoo + 1 comment The first one is indeed overly complex, as it would search the max at each iteration

I used the reduce function instead, which allows for a single iteration, provided an extra local variable, like so

`function birthdayCakeCandles(ar) { let max = 0; return ar.reduce( (count, i) => i === max ? count + 1 : i > max ? (max = i) && 1 : count, 0 ); }`

zimmah + 0 comments You can do it like this too:

const birthdayCakeCandles = a => (f => a.filter(v => v === f).length)(Math.max(...a));

cnps_bjjfan + 1 comment I did exactly what you did, but half the test failed and couldn't figure out why :P

zimmah + 0 comments Because it's horribly ineffiecient, causing it to time out (it takes more then 12 seconds so hackerrank cuts off the calculation to not waste processing power)

Because for every single item in the array it recalculates Math.max on the entire array, that's incredibly wastefull.

zimmah + 0 comments That oneliner kind of works, but it's extremely slow because it recalculates Math.max(ar) for every single item.

You can avoid that by storing the value of Math max like this:

const birthdayCakeCandles = a => (f => a.filter(v => v === f).length)(Math.max(...a));

That way it's still short, but also blazing fast. (Math max is implicitly stored as

`f`

here).

n_haque + 0 comments Oh filter and result.length is so much simpler! Mine was a little longer

function birthdayCakeCandles(ar) { let tallest = Math.max(...ar) let candleCount = 0 ar.forEach((candle) => candle === tallest ? candleCount++ : null) return candleCount }

careddu_m85 + 1 comment I used reduce to obtain the max, since spread operator can actually cause a stack overflow for large arrays.

josiah_mokobo + 1 comment function birthdayCakeCandles(ar) { return ar.filter(height => height === Math.max(...ar)).length }

josiah_mokobo + 0 comments You can filter out the max numbers from the array, and return its occurrance

bryank + 0 comments You can make it shorter with a bit of chaining.

function birthdayCakeCandles(ar) { const max = Math.max(...ar); return ar.filter(c => c === max).length; }

Kanahaiya + 1 comment Hello friends,

Birthday cake candles hackerrank problem can be solved easily by using one for loop. The complexity of birthday cake candles hackerrank solution is O(n)

If interested to know more about the generic algorithm in details-

click here for the

**video explanation of generic algorithm**with complexity analysis.or you can click on the image too to follow youtube tutorial.

**Here is the working solution:-****source code :**static int birthdayCakeCandles(int[] ar) { int maxCandleHeight = Integer.MIN_VALUE; int maxCandleFreqCount = 0; for (int i = 0; i < ar.length; i++) { if (ar[i] == maxCandleHeight) { maxCandleFreqCount++; } if (ar[i] > maxCandleHeight) { maxCandleHeight = ar[i]; maxCandleFreqCount = 1; } } return maxCandleFreqCount; }

Would really appreciate your feedback like, dislike , comment etc. on my video.

# Do not forget to upvote, if you find it useful.

kaleeswaran35 + 1 comment Thanks for your insight Kanahaiya Gupta

Kanahaiya + 0 comments most welcome. if you dont mind.Would really appreciate your feedback like, dislike , comment etc. on my video.

leo_kamwathi + 2 comments HINT: If you get a timeout. Avoid using complex methods. Keep it simple.

soumith_kosaraju + 1 comment Didnt know .max() method was 'complex', thanks. Life = saved :)

zimmah + 0 comments It's not complex, you just need to store it. Instead of doing the same calcultion every time.

parkerbeck88 + 0 comments I didn't account for cases where my niece is turning 100,000.

marinskiy + 2 comments Here is

**Python 3**solution from my HackerrankPractice repository:n = int(input()) ar = list(map(int, input().split())) print(ar.count(max(ar)))

Feel free to ask if you have any questions :)

voodoorrj1990 + 0 comments [deleted]Tej_Pratap_Singh + 0 comments @marinskiy Are you still updating your repo from time to time?

lakshminarayan77 + 2 comments Problem with Test case 8 is there any thing diffrent in that test case??

NewSumanM + 0 comments Yes they use different types of inputs every time

brian85 + 2 comments I tried to mimic the test case 8. My solution didn't work either and its total hack!

`function birthdayCakeCandles(ar) { const isEdge = typeof parseInt(inputString[0], 10) === 'number' && inputString.length === 2 && inputString[1].split(' ').length > 0 ? true : false; const size = isEdge ? parseInt(inputString[0], 10) : ar.length; const tallest = ar.sort().reverse()[0]; const output = ar.reduce((acc, n) => { acc = n === tallest ? acc + 1 : acc; return acc; }, 0); console.log(output > size ? size: output) return output > size ? size : output; }`

I'm not sure what's going on either.

I tried this case:

`200 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000`

It works and gives the answer 200 (there is 203 entries). however using the other one it crashes. The text file is too big to test in the editor.

[EDIT]

Figured it out

brian85 + 0 comments Issue was with Reversing the Array. Looks like it gets confused which array its revering. Wrapping in brackets was not enough. It seems like JS can't sort it correctly for some reason. I checked and every entry is type number so I'm not sure why .sort().reverse() doesn't work and why it needs to be in a bracket.

`function birthdayCakeCandles(ar) { const size = ar.length; const candles = ar; const tallest = (candles.sort((a, b) => { return b - a; }))[0]; const output = candles.reduce((acc, n) => { acc = n === tallest ? acc + 1 : acc; return acc; }, 0); return output > size ? size : output; }`

juanitoyuco + 0 comments The question is how to proceed. The test cases were too large and causing a time out. Please help.

Sort 1790 Discussions, By:

Please Login in order to post a comment