06/2/19

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. When she opens the book, page 1 is always on the right side.

Link

Drawing Book

Complexity:

time complexity is O(1)

space complexity is O(1)

Execution:

Integral division here again. No padding required.

Solution:
#!/bin/python

import sys

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

n = int(raw_input().strip())
p = int(raw_input().strip())
result = solve(n, p)
print(result)

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

Facebooktwittergoogle_plusredditpinterestlinkedin
06/2/19

HackerRank ‘Sock Merchant’ Solution

Short Problem Definition:

John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

Link

Sock Merchant

Complexity:

time complexity is O(N)

space complexity is O(N)

Execution:

Group the same color together. Look out for the integer division // that discards the odd socks.

Solution:
#!/bin/python

import sys
from collections import defaultdict

n = int(raw_input().strip())
c = map(int,raw_input().strip().split(' '))

d = defaultdict(int)
for k in c:
    d[k] += 1
    
cnt = 0
for ele in d.values():
    cnt += ele//2
    
print cnt

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

Facebooktwittergoogle_plusredditpinterestlinkedin
06/2/19

HackerRank ‘Bon Appétit’ Solution

Short Problem Definition:

Anna and Brian are sharing a meal at a restaurant and they agree to split the bill equally. Brian wants to order something that Anna is allergic to though, and they agree that Anna won’t pay for that item. Brian gets the check and calculates Anna’s portion. You must determine if his calculation is correct.

Link

Bon Appétit

Complexity:

time complexity is O(N)

space complexity is O(1)

Execution:

Follow the specification.

Solution:
#!/bin/python

n, k = map(int, raw_input().split())
c = map(int, raw_input().split())
charge = input()

should_have = (sum(c) - c[k])/2
diff = charge - should_have
if not diff:
    print "Bon Appetit"
else:
    print diff

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

Facebooktwittergoogle_plusredditpinterestlinkedin
05/23/19

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.

Link

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.

Facebooktwittergoogle_plusredditpinterestlinkedin
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.

Link

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)[0][0]

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 = [0] * 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.

Facebooktwittergoogle_plusredditpinterestlinkedin
05/21/19

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.

Link

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.

Facebooktwittergoogle_plusredditpinterestlinkedin
05/20/19

HackerRank ‘Left Rotation’ Solution

Short Problem Definition:

left rotation operation on an array shifts each of the array’s elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].

Link

Arrays: Left Rotation

Complexity:

time complexity is O(N)

space complexity is O(N)

Execution:

Solutions like this is where python really shines. Simple and straight forward.

Solution:
#!/bin/python

import math
import os
import random
import re
import sys

# Complete the rotLeft function below.
def rotLeft(a, d):
    return a[d:] + a[:d]

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

    nd = raw_input().split()

    n = int(nd[0])

    d = int(nd[1])

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

    result = rotLeft(a, d)

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

    fptr.close()




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

Facebooktwittergoogle_plusredditpinterestlinkedin
05/17/19

HackerRank ‘Breaking The Records’ Solution

Short Problem Definition:

Maria plays college basketball and wants to go pro. Each season she maintains a record of her play. She tabulates the number of times she breaks her season record for most points and least points in a game. Points scored in the first game establish her record for the season, and she begins counting from there.

Link

Breaking The Records

Complexity:

time complexity is O(N)

space complexity is O(1)

Execution:

Just track the min and max.

Solution:
#!/bin/python

import sys

def getRecord(s):
    min_ele = s[0]
    max_ele = s[0]
    min_cnt = 0
    max_cnt = 0
    
    for ele in s:
        if ele > max_ele:
            max_ele = ele
            max_cnt += 1
        if ele < min_ele:
            min_ele = ele
            min_cnt += 1
    
    return [max_cnt, min_cnt]
    
n = int(raw_input().strip())
s = map(int, raw_input().strip().split(' '))
result = getRecord(s)
print " ".join(map(str, result))


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

Facebooktwittergoogle_plusredditpinterestlinkedin
05/16/19

HackerRank ‘Between Two Sets’ Solution

Short Problem Definition:

You will be given two arrays of integers and asked to determine all integers that satisfy the following two conditions:

  1. The elements of the first array are all factors of the integer being considered
  2. The integer being considered is a factor of all elements of the second array
Link

Between Two Sets

Complexity:

time complexity is O(A* (N+M))

space complexity is O(1)

Execution:

This challenge could also be solved using the Greatest Common Divisor. Given that the range of values is only [1,100], it is safe to assume that the naive solution will terminate within the time limit.

Solution:
#!/bin/python

import sys

def isValid(a, b, candidate):
    for a_ele in a:
        if candidate % a_ele != 0:
            return False
    for b_ele in b:
        if b_ele % candidate != 0:
            return False
    return True

n,m = raw_input().strip().split(' ')
n,m = [int(n),int(m)]
a = map(int,raw_input().strip().split(' '))
b = map(int,raw_input().strip().split(' '))

cnt = 0
for candidate in xrange(max(a), min(b)+1):
    if isValid(a, b, candidate):
        cnt += 1

print cnt


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

Facebooktwittergoogle_plusredditpinterestlinkedin
05/6/19

Posting Schedule Sprint/Summer 2019

This page has 85 HackerRank Tasks posted as of May 2019. After looking over my HR profile, I noticed that I had solved a total of 200 Tasks there. In other words, I have not posted the majority of them 🙂

I have also run out of Tasks marked as Easy. I still have around 60 Medium ones that need solving.

It is unlikely, that I can just clean all of that up in a single session. I have therefore created a posting rhythm that should allow me to get all that code up here within a reasonable time frame.

I will be posting five posts every week until the end of September. Four of those will be Tasks that I have solved in the past, and only minor cleanups are required. Additionally, I will be posting one new Medium or harder Task every week.


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

Facebooktwittergoogle_plusredditpinterestlinkedin