07/26/20

# HackerRank ‘Drawing Book’ Solution

##### Short Problem Definition:

Brie’s Drawing teacher asks her class to open their books to a page number. Brie can either start turning pages from the front of the book or from the back of the book. She always turns pages one at a time.

Drawing Book

##### Complexity:

time complexity is O(1)

space complexity is O(1)

##### Execution:

Think of this as a 0-indexed book. Use integer division.

##### Solution:
```def solve(n, p):
last_letter = n // 2
goal_letter = p // 2
return min(goal_letter, last_letter-goal_letter)
```

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

07/26/20

# HackerRank ‘Counting Valleys’ Solution

##### Short Problem Definition:

Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly n steps. For every step he took, he noted if it was an uphill, U, or a downhill, D step. Gary’s hikes start and end at sea level and each step up or down represents a  unit change in altitude. We define the following terms:

• mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
• valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.

Counting Valleys

##### Complexity:

time complexity is O(N)

space complexity is O(1)

##### Execution:

I am a hiker myself, so this challenge is kinda funny. The description looks complex, but realistically one only needs to calculate whether the section was above or below sea level.

##### Solution:
```def countingValleys(n, s):
level = 0
valleys = 0
for direction in s:
if direction == "U":
level += 1
if level == 0:
valleys += 1
else:
level -= 1

return valleys
```

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

07/26/20

# HackerRank ‘Electronics Shop’ Solution

##### Short Problem Definition:

Monica wants to buy a keyboard and a USB drive from her favorite electronics store. The store has several models of each. Monica wants to spend as much as possible for the 2 items, given her budget.

Given the price lists for the store’s keyboards and USB drives, and Monica’s budget, find and print the amount of money Monica will spend. If she doesn’t have enough money to both a keyboard and a USB drive, print `-1` instead. She will buy only the two required items.

Electronics Shop

##### Complexity:

time complexity is O(N*M)

space complexity is O(1)

##### Execution:

The solution has a N*M complexity. If the range for B was significantly smaller, one could consider alternatives.

##### Solution:
```def getMoneySpent(keyboards, drives, s):
spend = -1

for v1 in keyboards:
for v2 in drives:
if v1 + v2 <=s:
spend = max(spend, v1 + v2)

return spend
```

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

07/26/20

# HackerRank ‘Cats And A Mouse’ Solution

##### Short Problem Definition:

Two cats and a mouse are at various positions on a line. You will be given their starting positions. Your task is to determine which cat will reach the mouse first, assuming the mouse doesn’t move and the cats travel at equal speed. If the cats arrive at the same time, the mouse will be allowed to move and it will escape while they fight.

Cats and a Mouse

##### Complexity:

time complexity is O(N)

space complexity is O(1)

##### Execution:

This one is trivial.

##### Solution:
```def catAndMouse(x, y, z):
catA = abs(x-z)
catB = abs(y-z)
if (catA < catB):
return "Cat A"
elif (catB < catA):
return "Cat B"
else:
return "Mouse C"
```

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

05/23/20

# HackerRank ‘Day Of The Programmer’ Solution

##### Short Problem Definition:

Marie invented a Time Machine and wants to test it by time-traveling to visit Russia on the Day of the Programmer (the 256th day of the year) during a year in the inclusive range from 1700 to 2700.

Day of The Programmer

##### Complexity:

time complexity is O(-1)

space complexity is O(-1)

##### Execution:

As I have pointed out in the past, no engineer should ever implement any calendar related functions. It should be done natively by the language or by a library.

I am fairly certain that the conventions will change by 2700 🙂 and the calculation will be invalid.

##### Solution:
```#!/bin/python

import math
import os
import random
import re
import sys

# Complete the dayOfProgrammer function below.
def dayOfProgrammer(year):
raise SystemError("This challenge is stupid")

if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

year = int(raw_input().strip())

result = dayOfProgrammer(year)

fptr.write(result + '\n')

fptr.close()
```

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

05/21/20

# HackerRank ‘Birthday Chocolate’ Solution

##### Short Problem Definition:

The member states of the UN are planning to send 2 people to the moon. They want them to be from different countries. You will be given a list of pairs of astronaut ID’s. Each pair is made of astronauts from the same country. Determine how many pairs of astronauts from different countries they can choose from.

Birthday Chocolate

##### Complexity:

time complexity is O(N)

space complexity is O(1)

##### Execution:

Keep track of Melements at a time. Basically a simplified prefix sum.

##### Solution:
```#!/bin/python

import sys

def getWays(squares, d, m):
cnt = 0
q = squares[:m-1]
for ele in squares[m-1:]:
q.append(ele)
if (sum(q) == d):
cnt += 1
q.pop(0)
return cnt

n = int(raw_input().strip())
s = map(int, raw_input().strip().split(' '))
d,m = raw_input().strip().split(' ')
d,m = [int(d),int(m)]
result = getWays(s, d, m)
print(result)
```

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

05/15/20

# HackerRank ‘Picking Numbers’ Solution

##### Short Problem Definition:

Given an array of integers, find and print the maximum number of integers you can select from the array such that the absolute difference between any two of the chosen integers is less than or equal to 1.

Picking Numbers

##### Complexity:

time complexity is O(N)

space complexity is O(N)

##### Execution:

Calculate the occurrence of every element. The largest subset is the sum of two adjacent elements. For simplicity, I calculate the result in the same loop. It could be split out.

##### Solution:
```from collections import defaultdict

def pickingNumbers(a):
d = defaultdict(int)
r_val = 0
for val in a:
d[val] += 1
r_val = max(r_val, d[val]+d[val+1], d[val]+d[val-1])

return r_val
```

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

05/13/20

# HackerRank ‘Apple and Orange’ Solution

##### Short Problem Definition:

Sam’s house has an apple tree and an orange tree that yield an abundance of fruit. In the diagram below, the red region denotes his house, where s is the start point, and i is the endpoint. The apple tree is to the left of his house, and the orange tree is to its right. You can assume the trees are located on a single point, where the apple tree is at point a, and the orange tree is at point b.

Apple And Orange

##### Complexity:

time complexity is O(N)

space complexity is O(1)

##### Solution:
```def solve(house_left, house_right, tree, elements):
cnt = 0
for ele in elements:
if tree+ele >= house_left and tree+ele <= house_right:
cnt += 1
return cnt
```

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

05/12/20

##### Short Problem Definition:

HackerLand University has the following grading policy:

• Every student receives a grade in the inclusive range from 0 to 100.

##### Complexity:

time complexity is O(N)

space complexity is O(N)

##### Execution:

Follow the problem specification. The solution could be further optimized to remove all unnecessary copies and the whole res array.

##### Solution:
```#!/bin/python

from __future__ import print_function

import os
import sys

#
# Complete the gradingStudents function below.
#
res = []
return res

if __name__ == '__main__':
f = open(os.environ['OUTPUT_PATH'], 'w')

n = int(raw_input())

for _ in xrange(n):

f.write('\n'.join(map(str, result)))
f.write('\n')

f.close()
```

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

05/22/19

# HackerRank ‘Migratory Birds’ Solution

##### Short Problem Definition:

You have been asked to help study the population of birds migrating across the continent. Each type of bird you are interested in will be identified by an integer value. Each time a particular kind of bird is spotted, its id number will be added to your array of sightings. You would like to be able to find out which type of bird is most common given a list of sightings. Your task is to print the type number of that bird and if two or more types of birds are equally common, choose the type with the smallest ID number.

Migratory Birds

##### Complexity:

time complexity is O(N)

space complexity is O(1)

##### Execution:

I provide two solutions to this challenge. Solution #1 is using the Counter collection in python and works well.

The second solution is more explicit and takes advantage of the restrictive challenge specification.

##### Solution:
```#!/bin/python

import math
import os
import random
import re
import sys
from collections import Counter

# Complete the migratoryBirds function below.
def migratoryBirds(arr):
mc = Counter(arr)
return mc.most_common(1)

if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

arr_count = int(raw_input().strip())

arr = map(int, raw_input().rstrip().split())

result = migratoryBirds(arr)

fptr.write(str(result) + '\n')

fptr.close()
```
```# Complete the migratoryBirds function below.
def migratoryBirds(arr):
frequencies =  * 6

for ele in arr:
frequencies[ele] += 1

max_val = 0
max_idx = 5

for idx in xrange(5, 0, -1):
if frequencies[idx] >= max_val:
max_idx = idx
max_val = frequencies[idx]

return max_idx
```

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.