# Birthday Chocolate

# Birthday Chocolate

Saikumar_P + 29 comments int getWays(int n, int* squares, int d, int m){ // Complete this function int sum[105]; int count=0; sum[0]=0; for(int i=0;i<n;i++)sum[i+1]=sum[i]+squares[i]; for(int i=0;i<=n-m;i++){ if(sum[i+m]-sum[i]==d){ count++; } } return count; }

shubham21 + 3 comments nice logic. +1

NiceBuddy + 3 comments [deleted]milczarek_r + 6 comments Same approach, but with iterators instead.

int solve(int n, vector < int > s, int d, int m){ int ways = 0; for(auto it = s.cbegin(); it != s.cend(); ++it){ if(d == std::accumulate(it, it + m, 0)) ways++; } return ways; }

viigihabe + 0 comments [deleted]tpacker + 2 comments I believe this is O(n^2). O(n) is also possible.

gk_2000 + 1 comment The OP is O(n)

victorz + 1 comment It's O(nm).

kjkanishk211194 + 0 comments its o(n^2), coz in worst case senario, all the choclate blocks would add up to d.

bineykingsley36 + 1 comment I have implemented it in O(n).

kjkanishk211194 + 0 comments can you show your logic ???

Spleen + 0 comments Why call accumulate function every iteration when you add only one square ? It's not the same approach : you are O(nlog(n)), his solution is in O(n)

24god10 + 0 comments can U explain me about 2 lines of your code?:

`for(auto it = s.cbegin(); it != s.cend(); ++it){ if(d == std::accumulate(it, it + m, 0))`

I think a`accumulate`

will sum element out of vector, I think it will be`it != cend() - m`

more saver.mehdi_jafaree131 + 0 comments Greate! Nice usage of accumulate!

janis_stolzenwa1 + 1 comment what you did but more readable:

`int birthday(vector s, int d, int m) { int n = 0; for(int i = 0; i <= s.size() - m;i++){ if( d == accumulate(s.begin() +i, s.begin() + i + m, 0)){ n++;`

} } return n;}janis_stolzenwa1 + 1 comment sorry, dont know how to make the code look nice in this forum :-/

prateeksaxena731 + 0 comments [deleted]

bryon_nicoson + 10 comments same approach in Java

static int solve(int n, int[] s, int d, int m){ int total=0; for (int i=0;i<=n-m;i++){ if(Arrays.stream(s, i, i+m).sum() == d) total++; } return total; }

Shubhanka + 1 comment Please explain the logic behind it.

ramji_vishnu_26 + 1 comment @shubhanka Using Arrays.stream method he sends a Array 's', starting index 'i' end index 'i+m' as range which returns a set of integers from Array 's' for that specified range then using sum() method he checks the sum to equals 'd', if conditon satifies it increase the total plus one.

kuntalravi91 + 2 comments *

*starting index is i=0 and end index is i+m=2 so the 2 index is excluded?? **bryon_nicoson + 2 comments the index range is inclusive of the start and end indices: [0, 1, 2].

we are looking at the set of chocolates from i to i+m and determining if that set meets our criteria. if it does, we increment total.

**then we increment i and look at the next set**, and so on until we have traversed the array.i like victorz's analogy below: it is a "sliding window."

i hope that helps.

grandmoffrapkin + 1 comment For the same program, how can we get the result if the required chocolate squares are not consecutive?

kjkanishk211194 + 0 comments thats not what the problem states ( these types of problem are called maximum-sub array problems ) ,

Still you want to solve this problem, you need to use Combinations, which will increase the diffuculty.

aborjrcl + 0 comments what is the i < n-m?

tiwari_ravikumar + 0 comments Yes the 2 index is excluded.

asmai_faical + 0 comments Java 8 is always here , thank you :)

azizxon_uz + 1 comment what if we must find when numbers not consecutive?

for example input:

10

5 3 1 4 2 5 1 2 4 2

8 2

there we can got 8 like that:

5 3

4 4pandaanurag0920 + 1 comment why i<=n-m is used for?

mehul_sachdeva7 + 0 comments because the last pair formed will be of the size m and we need out loop to go till n-m . if we go forward (n-m) even one step then m size of pair will not be formed as there are no more elements in array

mehul_sachdeva7 + 7 comments JS approach

function birthday(s, d, m) { var count = 0; for (var i = 0; i < s.length - m + 1; i++){ var sum = 0; for (var j = 0; j < m; j++){ sum = sum + s[i + j]; } if (sum == d) { count++; } } return count; }

csk111165 + 0 comments Nice Logic!

prashant70_pk + 0 comments really nice logic..Thanks(:..

yikming + 2 comments I think s.length - m + 1 is not necessary, can be just s.length.

24god10 + 0 comments Can I ask you why? Because I think the condition:

`<= s.length - m`

will make the accumulate in belong the size of vector, I dont understand a code with same like you said like this:`int solve(int n, vector < int > s, int d, int m){ int ways = 0; for(auto it = s.cbegin(); it != s.cend(); ++it){ if(d == std::accumulate(it, it + m, 0)) ways++; } return ways; }`

Harsh_Prajapati + 0 comments it is necessry beacuse when you are not writing then error is index out of bound

pa980403 + 0 comments Thanks mate!!

chulbulji67 + 0 comments int i,j,sum,count=0,n=s_count; for(i=0;i<=n-m;i++) { sum=0; for(j=i;j

tmcuong + 0 comments Mine is in a fimiliar way.

let count = 0; for (let i = 0; i <= s.length - 1; i++) { let sum = 0; for (let y = 0; y < m; y++) { sum += s[i+y]; } if (sum == d) { count += 1; } } return count;

peter_solays14 + 0 comments what if the sum exceed the d before the m is looped till the end!!! we can ignore further looing and make it more effecient !!

Spleen + 0 comments Don't call sum() every time Oo You add only one square each time ! (reduction cost log(n) computation) â†’ O(nlog(n)) It's possible in O(n) complexity

gabrielbb0306 + 0 comments Is it me or this is not the "same approach"? Correct me if i'm wrong but i think Arrays.stream.sum() iterates fron index a to b, so in every iteration of the for loop you are iterating again. Your algorithm is not 0(n) as @Saikumar_P's. This is my 0(n) solution with Java similar to @Saiumar_P's:

static int birthday(List s, int d, int m) {

`int[] sums = new int[s.size() + 1]; int count = 0; for(int i = 0; i < s.size(); i++) { int sumsIndex = i + 1; sums[sumsIndex] = sums[sumsIndex - 1] + s.get(i); if (sumsIndex >= m && (sums[sumsIndex] - sums[sumsIndex - m]) == d) count++; } return count; }`

shradha070801 + 0 comments What is n here?

jacobkalas + 0 comments Beautiful solution, one thing learned today! Thank you!

jacobkalas + 0 comments So i have implemented this piece of code but keep getting an error: "no suitable method found for stream(List,int,int)"

cvilladiegoa + 1 comment Same approach in C#

int total = 0; for(int i = 0; i <= s.Count - m; i++) { var segsSum = s.GetRange(i, m).Aggregate((a, b) => a + b); if(segsSum == d) { total++; } } return total;

rohanghule12 + 0 comments In C++

int count = 0; for (int i = 0; i < s.size() - m + 1; i++) { int sum = 0; for (int j = 0; j < m; j++) { sum = sum + s[i + j]; } if (sum == d) { count++; } } return count;

aravind295 + 0 comments [deleted]aravind295 + 1 comment `static int birthday(List<Integer> s, int d, int m) { int sum = 0,ways=0; for (int i=0;i<m;i++){ sum += s.get(i); } for (int i=0;i<s.size()-m+1;i++) { if (sum==d) { ways++; } if (i+m <s.size()){ sum =sum-s.get(i)+s.get(i+m); } } return ways; }`

dejavxtrem + 0 comments Please can you explain your code in details

victorz + 2 comments I used a sliding window, just like you, but there was no need to build a sum array.

https://www.hackerrank.com/challenges/the-birthday-bar/submissions/code/43358272sayanmanik_sm + 1 comment how is the logic working?

victorz + 1 comment It's a

**sliding window**.CurlyHurlyGirl + 1 comment Can you tell me how the logic works? I'm new and have many to learn.

victorz + 0 comments If you already have the sum of a subarray (like the starred elements in

`[***___]`

), then you can get sum of the subarray with indices shifted right by 1 (for the previous example,`[_***__]`

) by adding one element and subtracting another.Prince_sai's solution gets O(n) runtime in a different way: a cumulative sum array.

15B01A0577 + 0 comments how did u get dat kinda logic

Sentinal_prime + 1 comment please explain the logic

khirulislam_cse + 7 comments Here is the Java implemetation. We just need the starting index that we are working on. and every time there is an ArrayIndexOutofBoundsException that means we don't need the loop anymore and we break. We count the total of consecutive squares and check if it's equal to the d.

static int solve(int n, int[] s, int d, int m){ int startingIndex =0; int result =0; int total = 0; for(int i=0;i<n;i++){ startingIndex = i; try{ for(int j=0;j<m;j++){ total += s[startingIndex + j]; } }catch(Exception e){ break; } if(total == d){ result++; } total =0; } return result; }

codertoaster + 5 comments I have the same idea as you, but why are most of my test cases failing ?

static int solve(int n, int[] s, int d, int m) { int start=0,end=m-1; int sum=0,num=0; for(int i=start ; i<=end && end<s.length ; i++) { sum+=s[i]; if(i==end) { if(sum == d) { num++; sum=0; i=start+1; start++; end++; } else { sum=0; i=start+1; start++; end++; } } } return num; }

pankajbabu + 3 comments i use yur code,but test case is fails.....so improve your codess.. thanks

pooniaarvind29 + 0 comments thug life

rearbreed + 0 comments lol

btiwari004 + 0 comments lol

aishwarya217 + 1 comment Hey, it's probably not working because in this code

**i**is getting changed to**start + 1**and then getting incremented again as part of the**for**loop.if(sum == d) { num++; sum=0; i=start+1; start++; end++; } else { sum=0; i=start+1; start++; end++; }

Hope this helps.

moihawk + 0 comments thats what it was for me, thank you

rvrishav7 + 1 comment int main() { int n; cin>>n; int ar[n]; int i,c=0; for(i=0;i<n;i++) cin>>ar[i]; int d,m; cin>>d>>m; int s=0,l=1; i=0; while(m<=n) {l=0;s=0; while(l<m) { s=s+ar[l+i]; l=l+1; } if(s==d) { c=c+1; } i=i+1; n=n-1; } cout<<c; return 0; }

abhi_satya1357 + 0 comments # include

using namespace std;

int main() { int i,n,sum=0,date,month,num[1000],count=0,j; cin>>n; for(i=0;i>num[i]; } cin>>date>>month; for(i=0;i

romulo8000 + 1 comment A good constructive tip: extract common code like:

if(sum == d) { num++; } else { start++; } i=start+1; sum=0; start++; end++;

It's More readable

tejpratapp468 + 0 comments superb logic int birthday(vector s, int d, int m) { int p=s.size();int i,j; int sum=0; int count=0;int start=0; for(i=0;i

} return count;

}

kevinhs472 + 0 comments Nice logic man, i learn some new tips there.thank you for posting this.

krmatalia + 1 comment int c=0; for(int i=0;i<n;i++) { int sum=0,j=i,lp=0; if((j+m)>=n && (j+m)!=1) break; else { while(lp<m) { sum+=s[j++]; lp++; if(sum==d) ++c; } } } return c;

even this is failing i don't know why when i purchased the testcases i was getting the right output.

codertoaster + 0 comments yeah that happens a lot. my outputs are same as the test cases still shows failure.

harshitha2922 + 0 comments thanks for an easy understood algorithm !

dparthib + 0 comments Nice code:

If you change your code as below suggestion then no need to handle the exception.

for(int j=0;(j<n)&&(j<m);j++)

ramji_vishnu_26 + 0 comments @Khirulislam_cse You can avoid using the entire try catch block by replacing with simple while loop statement.

Shubham_203 + 0 comments Hie,see this java implementation

static int solve(int n, int[] s, int d, int m){ // Complete this function int sum,count=0,j,k; for(int i=0;i<=n-m;i++) { k=i; sum=0; j=1; while(j<=m) { sum=sum+s[k]; k++; j++; } if(sum==d) count++; } return count; }

phatngo1606 + 0 comments Your code is so wonderfullll

sonupanchal + 0 comments [deleted]Nidhi99 + 0 comments Why is sum an array of 105 integers? Isn't 101 enough?

ash_upadhyay + 7 comments def solve(n, s, d, m): # Complete this function count = 0 for i in range(0,n): total = sum(s[i:m+i]) if total == d: count+=1 return count

This function uses a sliding window too :) If any corrections please comment :)

tpacker + 2 comments I believe this is O(n^2). O(n) is also possible.

ash_upadhyay + 1 comment @tpacker Thanks. I appreciate your response. Can you please help me understand how can we get O(n) I couldn't figure out what makes it O(n^2) any leads would really be appreciated :)

smhoyo + 4 comments So, your answer is not really O(n^2), but rather O(n*m), since your sum() method iterates over m elements in the array for every n element in the array. Thus, O(m*n).

You can improve though, if you figure out a smarter way to keep track of the sum of the m previous pieces. You can for example just hold a sum variable where you remove the last element and add the new one as you iterate, instead of calculating the whole sum each and every time. (Imagine the repeated work when your m grows).

Here is a java example:

static int solve(int n, int[] s, int d, int m){ int sum = 0; int r = 0; for (int i = 0; i < s.length; i++) { sum += s[i]; // M is never less than 1 if (i > m - 1) sum -= s[i - m]; if (i >= m - 1 && sum == d) r++; } return r; }

mountaingeek93 + 0 comments this is gold! thank you :)

victorz + 0 comments m <= n, so O(nm) is

*technically*O(n^2) too, but O(nm) is a tighter upper bound._rajulSingh + 0 comments wow

jaishreekulkarni + 0 comments Awesome solution. Some out of the box thinking there!!

Ajey01 + 0 comments yeah!!

suryabteja + 0 comments Why is that it doesn't through list index out of range error?

Shanthini_S + 0 comments [deleted]mahamadbilal696 + 0 comments [deleted]rakesht2499 + 3 comments The shortest method for the above python code

return sum(1 for x in range(len(s)) if sum(s[x:x+m]) == d)

lifebalance + 0 comments Well done!

wrutka + 1 comment Im not sure of this solution. This will not be working with this input:

5 1 2 1 3 3 3 2

The output should be

`2`

but will be`3`

because it will count last digit of the series`3`

. This solution does not consider what if solution will be shorter than a month digit.Sure, this will pass all validators but still... :).

daniel_augusto11 + 0 comments return sum(1 for x in range(len(s)) if sum(s[x:x+m]) == d and len(s[x:x+m]) == m )

DaniRed_ + 1 comment That't beutiful thank you for sharing : i did this way but we can make way shorter by yours..

- num=0
- for i in range(len(s)):
- if sum(s[i:i+m])==d:
- num+=1
- return(num)

DaniRed_ + 1 comment List comprehension is amazing

arshiyasoleimani + 0 comments I agree but also his method is n * m time complexity sadly.

irondsd + 0 comments This method wouldn't work if the numbers were not close together? I tested it for an array with suiting numbers in the opposite side of the array and sure enough it didn't work.

So, is there a way to find the anwer for this case?

kuzkingard + 0 comments This is brilliant!. Please can you shed an insight as to why you used the index range i:m+i in line 5?

smhoyo + 1 comment My solution in Java:

static int solve(int n, int[] s, int d, int m){ int sum = 0; int r = 0; for (int i = 0; i < s.length; i++) { sum += s[i]; // M is never less than 1 if (i > m - 1) sum -= s[i - m]; if (i >= m - 1 && sum == d) r++; } return r; }

victorz + 0 comments This one uses a sliding window, just like my solution. I did it slightly differently by summing the first m digits in another loop.

johnmensah + 2 comments why not O(n) like below

def solve(n, s, d, m): if(n==1 and s[0]==d): return 1 elif(n==1): return 0 count = 0 for i in range(len(s)-1): if(sum(s[i:m+i])==d): count = count + 1 return count # Complete this function

mahamadbilal696 + 1 comment we should select the proper range otherwise the list becomes out of order, but in this example no need(can select range(0, n))

`def birthday(s, d, m, n): count = 0 for i in range(n-m+1): if(sum(s[i:m+i])==d): count = count + 1 return count`

Any quasions, fell free to ask.

quaid_johar33 + 1 comment perfect code

arshiyasoleimani + 0 comments Very inefficent.

not_neophyte + 0 comments can anyone pls explain how does this code work?

priyachowdary191 + 1 comment will you please explain why did you write this:sum[i+m]-sum[i]==d

Ajey01 + 0 comments i didn't have written this line.....plzz check once

shreyagarwal611 + 0 comments nice logic broo!!!

aiswarya110498 + 0 comments change getWays function into birthday function.. Answer is right.. Could you please explain the logic behind declaring sum[105] ?

bineykingsley36 + 1 comment nice logic. However can you reduce the time complexity a little?

victorz + 0 comments No, it's already O(n).

Thinkster + 0 comments Ruby!

def birthday(bar, day, month) possible = 0 (0..bar.length - month).each do |i| possible += 1 if (bar[i...i + month].inject(0, :+) === day) end possible end

amyanktiwari + 0 comments Can you explain me the question in easy language ,i mean what we have to do.

harshnagpal10 + 0 comments please explain the logic

harshnagpal10 + 0 comments nice pal

kvbabu02461 + 0 comments could you explain the second for loop

kmtstemail + 0 comments `static int birthday(List<Integer> s, int d, int m) { int count = 0; for(int i=0; i<= s.size() - m; i++) { if( s.subList(i, i+m).stream().mapToInt(n -> n).sum() == d) { count++; } } return count; }`

mishrashivanshu + 0 comments May I get Algo Explaination pls...

imnetanmangal + 0 comments I think you must run outer FOR loop "i < n-1" times instead of "i < n"

sarimahmad1509 + 0 comments Nice, logic bro!!! But I have a question y u have tkn the size of sum array as 105. Can't we take it as size of squares array +1 ? sum[arrays.length+1];

durgeshp + 0 comments Bhai Kamaal kar diye tum!!! (Wow what a logic!!!!) Jabardast!!! (well done!!)

yanjanendra + 0 comments # If anyone need help on JS

guptadevansh73 + 0 comments # include

using namespace std; int main() { int n,s[100],d,m,i,j,sum=0,ct=0; cin >> n; for(i=0;i> s[i]; } cin >> d >> m; for(j=0;j<=n-m;j++) { for(i=j;i

guptadevansh73 + 1 comment # include

using namespace std; int main() { int n,s[100],d,m,i,j,sum=0,ct=0; cin >> n; for(i=0;i> s[i]; } cin >> d >> m; for(j=0;j<=n-m;j++) { for(i=j;i

guptadevansh73 + 0 comments plz tell whats wrong..????

tdhanush777 + 0 comments nice logic man

PkkdGuy + 9 comments Pyhton people see this!!

def getWays(squares, d, m): tp = (len(squares)-m) + 1 #total number of pieces possible return len([1 for i in range(tp) if sum(squares[i:i+m])==d])

saxtouri + 1 comment I did the same think with multiple lines, but it's always refreshing to see oneliner solutions.

tkomane + 3 comments Honestly I find one-liners a bit overrated. A lot of people on here get into this nasty habit of cramping their code just to force a one-liner - which I find just silly.

jon_black + 0 comments I agree and disagree. One-liners that don't obfuscate the code are succinct. You just have to make sure that property holds true, and that creating a one-liner doesn't decrease performance.

saxtouri + 0 comments One liners make a slipery slope when writting production code, but in games like this, it is just a nice excescise.

Pyjamadeus + 1 comment Seeking out a one-liner at the expense of efficiency (as we see here) seems a strange way to prioritise things, but oh well

sharmaspg + 1 comment how do you people get this logic ?is it pure practice or do you refer some books for the logic ?

SpaceHero + 1 comment I suppose practice. Practice list comprehensions enough and it can get easy. This is a list comprehension that adds 1 to a list everytime the sum in that range is equal to d. Then len is used to count all the 1s in that list. I learned list comprehensions through learning haskell.

frankhjung + 0 comments That is how I solved it using Haskell! https://www.hackerrank.com/challenges/the-birthday-bar/submissions/code/99568589 Though I would to love to know if there is a function (like scanl) that would generalise this ...

pnkj119 + 4 comments Beat this:

def getWays(squares, d, m): return sum([1 for i in range(n-m+1) if sum(s[i:i+m])==d])

PkkdGuy + 1 comment There is nothing to beat in your code bro :D

victorz + 3 comments You could use a generator expression instead of a list comprehension.

def getWays(squares, d, m): return sum(1 for i in range(n-m+1) if sum(s[i:i+m])==d)

But if you want a more efficient solution for larger inputs, use a sliding window (see the following link). https://www.hackerrank.com/challenges/the-birthday-bar/submissions/code/43358272

SebastianNielsen + 1 comment By "sliding window" don't you mean a loop whithin a loop, so that it counts a surden amount ahead for each item in the lst.

victorz + 1 comment By "sliding window", I mean one loop without nesting another loop within it. When you advance to the next item, you add one item and subtract another item.

jeremydcarr + 0 comments Yo, thanks for that description. I hadn't thought of that. Made the solution so much cleaner.

h201551072 + 1 comment can u explain ur code pls!!!!!

victorz + 0 comments There's nothing to explain; it's all obvious.

[deleted] + 0 comments return sum(sum(s[element:element+m) == d for element in range(len(s))])

vishoo7 + 0 comments This is adding from idx to idx + m. It's more efficient to keep a running sum and subtract the beginning of the window and add the next value:

def solve(n, s, d, m): if m > n: return 0 i = j = 0 window_sum = 0 while j < m: window_sum += s[j] j += 1 count = 1 if window_sum == d else 0 while j < n: window_sum -= s[i] window_sum += s[j] if window_sum == d: count += 1 i += 1 j += 1 return count

joshumcode + 1 comment I don't understand how this works given that n is not defined.

ganeshshinde1494 + 0 comments its lenght of given array. n=len(s)

alphasingh + 0 comments Python people saw this, and now python people jealous. :p

baymaxneoxys + 0 comments Thanks for the approach! BTW we could have used segment trees as well, right?

LeHarkunwar + 2 comments Did similarly, but shorter

def solve(n, s, d, m): return sum([1 for i in range(n-m+1) if sum(s[i:i+m]) == d])

victorz + 2 comments That's just a copy of https://www.hackerrank.com/challenges/the-birthday-bar/forum/comments/289156

LeHarkunwar + 0 comments Truly didn't see that, looks super similar :P

cfshao_bjtu + 1 comment I cannot see the results in the link. Could you please share your code here?

Thank you

cfshao_bjtu + 0 comments

bL4ck_r4bb1t + 0 comments In Python True == 1 and False == 0, so this also works:

def solve(n, s, d, m): return sum(sum(s[i: i + m]) == d for i in range(n - m + 1))

panda_whisperer + 1 comment Ruby version:

def solve(squares, d, m) squares.each_cons(m).map(&:sum).select { |s| s == d }.count end

brunoao86 + 0 comments +1

Ruby <3

juggmug + 0 comments how did u write tp?

arisiru + 0 comments In fact your solution is dumb, you solved it in O(n^2) instead of O(n)

alexdam321 + 0 comments Why does this work? In the case you have the list of squares [1,1, 3, 3, 2], m = 2 and d = 3, there are two positive cases of [2,1] and [1,2]. However, your code gives returns 0.

The only way this makes sense is the assumption the pieces must be consecutive to sum, but I didn't see that mentioned in the problem.

kcoddington0925 + 7 comments C# implementation:

using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution { static int getWays(int[] squares, int d, int m) { int ways = 0; for (int i = 0; i < squares.Length - (m - 1); i++) if (squares.Skip(i).Take(m).Sum() == d) ways++; return ways; } static void Main(String[] args) { int n = Convert.ToInt32(Console.ReadLine()); string[] s_temp = Console.ReadLine().Split(' '); int[] s = Array.ConvertAll(s_temp, Int32.Parse); string[] tokens_d = Console.ReadLine().Split(' '); int d = Convert.ToInt32(tokens_d[0]); int m = Convert.ToInt32(tokens_d[1]); int result = getWays(s, d, m); Console.WriteLine(result); } }

kandoimihir + 1 comment I know this is an old comment but I want to understand the logic behind this

squares.Length - (m - 1)

Can you help me?

StefanCFC + 1 comment If n = 19 and m = 7. You don't need to sum elements from index 13 to 18 because you don't have enough peaces of chocolate. I hope i helped you :D

kandoimihir + 0 comments Thank you :)

marlondias + 0 comments Cool LINQ! Thanks for sharing!

rodrigoramirez93 + 0 comments Solid as a rock, thanks for sharing

audusheriffemor1 + 0 comments Hello, I'm confused. Why did you have to subtract

*(m - 1)*from the length of the arrayivan_yuriev + 0 comments It could be simplified even more

`static int birthday(List<int> s, int d, int m) { return Enumerable.Range(0, s.Count - m + 1) .Select(x => s.Skip(x).Take(m).Sum()) .Count(x => x == d); }`

but this is not optimal solution performance vice - it do too much redundant sum calculations (see discussion above for details)

tvinay81 + 0 comments static int birthday(List s, int d, int m) { int sum = 0; int count = 0; int res = 0;

`for(int x = 0; x < s.Count-m+1; x++) { for(int y = x; y < s.Count; y++) { sum += s[y]; count++; if (sum == d && count==m) { sum = 0; count = 0; res++; break; } else if (sum > d) { sum = 0; count = 0; break; } } } return res; }`

thesmiths422 + 0 comments Great C# solution!

ejfamanas + 6 comments Javascript solution (tried to simplify as much as possible):

function solve(s, d, m) { let result = 0; for (let i = 0, l = s.length; i < l; i++) { if (s.slice(i, i + m).reduce((x, y) => x + y) === d) { result++; } } return result; }

m_kocijevsky + 0 comments I started with the same approach, but there is a gotcha in there.

**[1,2,3,4].slice(2,6)**will return**[3,4]**. So the length of a new array is only 2. Have no idea how to fix it so I decided to use the inner cycle.ancientsneeky + 0 comments If s was a sorted array this function would fail more than it would succeed

apolo4pena + 0 comments I did it pretty much the same way but slightly different. I like your chained functions in the evaluation!

function solve(s, d, m) { let vc = []; for (let i = 0; i < s.length; i++) { let c = s.slice(i, i + m); // if c the size of m and d equals c's sum then keep it if((c.length === m) && (d === c.reduce((a, p) => p + a, 0))){ vc.push(c); } } return vc.length; }

hroger19 + 0 comments In your for loop,

`i`

should stop when`i < = l - m`

? Or would your if statement not run if the segment is less than`m`

?ianbevel + 0 comments [deleted]gary_l_hewitt + 0 comments I like this approach; you could either set the endpoint of the

`for`

loop to`i<l-m`

or just compare`s.length==m`

in the`if`

to avoid going "off the edge."I found a very one-line functional approach, ugly but appealing all the same. I didn't put in the off-the-edge check for brevity :)

`return s.filter((e,i,a) => (a.slice(i,i+m).reduce((aa,cc)=>aa+cc)==d)).length`

lahouari + 8 comments My java simple way...

static int solve(int n, int[] s, int d, int m) { int result = 0; for (int i=0; i<n; i++) { int limit = i + m; if (limit > n) { break; } int sum = 0; for (int j=i; j<limit; j++) { sum += s[j]; } if (sum == d) { ++result; } } return result; }

ScienceD + 0 comments What do you think about recursive approach?

int solve(vector<int> s, int d, int m, int i) { if(i < s.size() - m + 1) { int sum = 0; for(int j = i; j < i+m; ++j) sum += s[j]; bool good_choco = sum == d; return good_choco + solve(s, d, m, i+1); } else return 0; }

lchoo1996 + 0 comments [deleted]priyangshuy + 0 comments love your code.

VirajSingh19 + 0 comments I was doing the same thing and my code was throwing array out of bounds exception. I don't know where I was wrong until I saw your code. It happens to me all the time.

harshshubh + 0 comments Thank you for your advice.

afederigo + 0 comments I have pressed dislike accidentally, sorry!

sss1721 + 0 comments Really awesome. Superb Logic

ylmazcandelen + 2 comments Did something smilar:

static int birthday(List<Integer> s, int d, int m) { int answer=0; int temp=0; for(int i=0;i<=s.size()-m;i++){ for(int t=i;t<i+m;t++){ temp+=s.get(t); } if(temp==d) { answer++; } temp=0; } return answer; }

afederigo + 0 comments It works. Thanks!

func birthday(s []int32, d int32, m int32) int32 { var i, answer, temp int32

`for i = 0; i <= int32(len(s)) - m; i++ { for j := i; j < i + m; j++ { temp += s[j] } if temp == d { answer++ } temp = 0 } return answer`

}

Shaurabh14 + 3 comments Very simple to understand solution.

`// Complete the birthday function below. static int birthday(List<Integer> s, int d, int m) { int length = s.size(); int numWays = 0, sum = 0; for(int i = 0 ; i <= (length - m) ; i++){ for(int j = 0 ; j < m ; j++){ sum = sum + s.get(j+i); } if(sum == d){ numWays++; } sum = 0; } return numWays; }`

[deleted] + 0 comments Please explain the logic behind it.

kmtstemail + 1 comment `static int birthday(List<Integer> s, int d, int m) { int count = 0; for(int i=0; i<= s.size() - m; i++) { if( s.subList(i, i+m).stream().mapToInt(n -> n).sum() == d) { count++; } } return count; }`

hafizmuhamadazam + 0 comments after solving I was reading comments, I was shocked seeing same solution I wrote.

`static int birthday(List<Integer> s, int d, int m) { int count = 0; for (int i = 0; i <= s.size() - m; i++) { if (d == s.subList(i, i + m). stream().mapToInt(Integer::intValue).sum()) count++; } return count; }`

Coder_AMiT + 1 comment One liner is always better, but i dont really like to compress the size, moreover this is more readable:

def getWays(squares, d, m): count = 0 for i in range(0,len(squares)+1-m): if sum(squares[i:i+m]) == d: count+=1 return count

girishpillai239 + 1 comment why is the range subtracted from len()+1?

Coder_AMiT + 0 comments so that when the sliciing happens on list squares[i:i+m] , it does not go above the index limit. as you can see i am doing i+m , while i is going from 0, to len() In such case, you need to reduce the window. This is known as Sliding window algorithm.

marinskiy + 4 comments Here is

**Python 3**solution from my HackerrankPractice repository:n, s = int(input().strip()), list(map(int, input().split())) d, m = map(int, input().split()) print(sum([sum(s[i : i + m]) == d for i in range(len(s) - m + 1)]))

Feel free to ask if you have any questions :)

thilak412 + 0 comments can you explain that please :-(

chauhanshivam_ + 0 comments **This is what i was looking for!****thanks!**vamsikrish04 + 0 comments [deleted]pWiszniewski + 0 comments It's O(n*m), can be done faster with O(n). One-liner doesn't make it good solution.

Mr__Ak + 1 comment Python3

n,a = int(input()),list(map(int,input().split())) d,m = map(int,input().split()) ans = 0 for i in range(len(a)): if sum(a[i:i+m]) == d: ans+=1 print(ans)

skukreja434 + 1 comment sum(a[i:i+m]) would you please explain this condition?

prithvireddy_ko1 + 0 comments hes fetching the sum of the sub array of size m using sum method

vlad_chankselia1 + 1 comment Python 3 one-liner:

return len([1 for i in range(len(s)-m+1) if sum(s[i:i+m])==d])

sunil1468 + 0 comments but sadly it's a O(n^2) solution.

Sort 1132 Discussions, By:

Please Login in order to post a comment