Viral Advertising : HackerRank Solution in Python

Shounak Lohokare
2 min readNov 4, 2020

HackerLand Enterprise is adopting a new viral advertising strategy. When they launch a new product, they advertise it to exactly 5 people on social media.

On the first day, half of those 5 people (i.e., floor(5/2)=2 ) like the advertisement and each shares it with 3 of their friends. At the beginning of the second day, floor(5/2) x 3 = 6 people receive the advertisement.

Each day, floor(recipients/2) of the recipients like the advertisement and will share it with 3 friends on the following day. Assuming nobody receives the advertisement twice, determine how many people have liked the ad by the end of a given day, beginning with launch day as day 1.

For example, assume you want to know how many have liked the ad by the end of the day.

Day Shared Liked Cumulative
1 5 2 2
2 6 3 5
3 9 4 9
4 12 6 15
5 18 9 24

The cumulative number of likes is 24.

Function Description

Complete the viralAdvertising function in the editor below. It should return the cumulative number of people who have liked the ad at a given time.

viralAdvertising has the following parameter(s):

  • n: the integer number of days

Solution in Python 3

First of all, we will store the number of people HackerLand Enterprise initially advertises to when they launch a new product in a variable called numOfPeopleAdvertised. Thus the expression will be:-

numOfPeopleAdvertised=5

Now we will declare a variable totNumOfPeopleLiked and assign zero to it.

totNumOfPeopleLiked=0

Then we will use a for loop to traverse n i.e on the day for which we have to calculate the total number of likes obtained by the advertisement. Thus the loop will be:-

for day in range(n):

In the for loop we will divide the numOfPeopleAdvertised by 2 using floor division and store it in a variable called numOfPeopleLiked, which as the variable name suggests will contain the number of people who have liked the advertisement. The above expression will be:-

numOfPeopleLiked = numOfPeopleAdvertised//2

Then we will use addition assignment to add the numOfPeopleLiked in totNumOfPeopleLiked. which will be expressed as:-

totNumOfPeopleLiked+=numOfPeopleLiked

Then we will obtain the number of people advertised on the following day by multiplying numOfPeopleLiked by 3.

numOfPeopleAdvertised = numOfPeopleLiked*3

Thus the for loop will be:-

At the end of the solution we will return totNumOfPeopleLiked.

Therefore the complete solution is:-

--

--

Shounak Lohokare

pretending to teach is one of the best way to learn.