Hackerrank's Problem Solving solutions( Viral Advertising, Save the Prisoner!, Circular Array Rotation ) :
Problem 31: Viral Advertising
Solution: (in c++)
( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)
This code is simple. There's no need for any explanation.
Problem 32: Save the Prisoner!
Solution: (in c++)
( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)
"From where the hell this formula came" , after reading the solution your mind will probably say that. Let me explain : here n = no. of prisoners , s = seat number from which we will start distributing , m = no. of candies.
Suppose we always start distributing from the first prisoner then in that case we will have use modulo if m is greater than the number of prisoners and since modulo is best when period starts from zero therefore let the first prisoner be at zeroth seat. The idea of modulo and s-1 came from here.
The m-1 handles the fact that the sweet which will be given to first prisoner( according to s value) is not counted when giving away sweets. for example suppose s = 8 and number of sweets are 2 therefore (8+m-1) ==> (8+2-1) ==> 9 i.e 9th seat member should be warned.
The +1 in the end is to compensate s-1 value since first seat no. is 1 and not 0.
Problem 33: Circular Array Rotation
Solution: (in c++)
( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)
This question is simple and uses the fact that after k rotations the zeroth element will come at index k ( when k is less than n ) or k%n (when k is greater than n) and of course we can use k%n even when k is less than n so therefore , we can say that zeroth element will come at index k%n after k rotations.
For example - a = [3,4,5] and k = 2 , therefore final array = [4,5,3] (3 came at index 2 or 2%3=2)
a = [3,4,5] and k = 4 , therefore final array = [5,3,4] (3 came at index 1 or 4%3=1)
Now we can set the elements lying ahead of it easily and we know if we reaches at the end we will have to go to the beginning to put the elements. That's what is done in the solution. We have placed the zeroth element of vector v at k%n index of the vector v2 and then placing all the elements in order till we reach the end of the vector v2 and if we encounter end (mo = = n) means now we have to put the elements from zeroth index keeping the order.
Guys , if you have any queries or need more explanation for something , comment below!
Comments
Post a Comment