08/28/20

# HackerRank ‘Fraudulent Activity Notifications’ Solution

##### Short Problem Definition:

HackerLand National Bank has a simple policy for warning clients about possible fraudulent account activity. If the amount spent by a client on a particular day is greater than or equal to 2x the client’s median spending for a trailing number of days, they send the client a notification about potential fraud. The bank doesn’t send the client any notifications until they have at least that trailing number of prior days’ transaction data.

##### Link

Fraudulent Activity Notification

##### Complexity:

time complexity is O(N^2)

space complexity is O(N)

##### Execution:

I am not very happy with this solution, but it passes the tests, so I am posting it. This solution is running in O(N^2) due to the element removal from the running_median. del l[i] is O(N). O(NlogN) would be preferable.

The expenditures are actually not very large numbers [0..200], so there might be space for optimization there.

##### Solution:
```from bisect import bisect_left, insort_left

def activityNotifications(expenditure, d):
warnings = 0

running_median = sorted(expenditure[:d])
for i,ele in enumerate(expenditure):
if i < d:
continue

if d % 2 == 1:
median = running_median[d//2]
else:
median = (running_median[d//2 - 1] + running_median[d//2])/float(2)

if ele >= median*2:
warnings += 1

# remove previous element
del running_median[bisect_left(running_median, expenditure[i-d])]

# add new element
insort_left(running_median, ele)

return warnings

```

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

08/21/20

# HackerRank ‘Box It!’ Solution

##### Short Problem Definition:

Design a class named Box whose dimensions are integers and private to the class.

Box It!

Does not apply.

Does not apply.

##### Solution:
```// The class should have the following functions :
class Box {
private:
int l=0;
int b=0;
int h=0;
public:
// Constructors:
// Box();
Box() = default;
// Box(int,int,int);
Box(int len, int bre, int hei):
l(len), b(bre), h(hei) {};
// Box(Box);
Box(Box &other):
l(other.l), b(other.b), h(other.h) {};

// int getLength(); // Return box's length
int getLength() { return l;}
// int getBreadth (); // Return box's breadth
int getBreadth() { return b;}
// int getHeight ();  //Return box's height
int getHeight() { return h;}

// long long CalculateVolume(); // Return the volume of the box
long long CalculateVolume() { return (long long) l*b*h;}

//Overload operator < as specified
//bool operator<(Box& b)
bool operator<(Box& b) {
return this->l < b.l ||
(this->b < b.b && this->l == b.l) ||
(this->h < b.h && this->b == b.b && this->l == b.l);
}
};

ostream& operator<<(ostream& out, Box& b) {
out << b.getLength() << " ";
out << b.getBreadth() << " ";
out << b.getHeight() << " ";

return out;
}
```

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

08/21/20

# HackerRank ‘C++ Rectangle Area’ Solution

##### Short Problem Definition:

Create two classes:

Rectangle
The Rectangle class should have two data fields-width and height of int types. The class should have display() method, to print the width and height of the rectangle separated by space.

RectangleArea
The RectangleArea class is derived from Rectangle class, i.e., it is the sub-class of Rectangle class. The class should have read_input() method, to read the values of width and height of the rectangle. The RectangleArea class should also overload the display() method to print the area width*height of the rectangle.

Rectangle Area

Does not apply.

##### Solution:
```// because cstdio is superior!
#include <cstdio>
/*
* Create classes Rectangle and RectangleArea
*/

class Rectangle {
public:
int width = 0;
int height = 0;

virtual void display() {
printf("%d %d\n", width, height);
}
};

class RectangleArea: public Rectangle {
public:
void read_input() {
scanf("%d %d", &width, &height);
}

void display() override {
printf("%d\n", width*height);
}
};
```

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

08/21/20

# Codility ‘ShortestAdjSeq’ Solution

##### Short Problem Definition:

A non-empty zero-indexed array A consisting of N integers is given. Two integers P and Q are called adjacent in array A if there exists an index 0 ≤ K < N−1 such that:

• P = A[K] and Q = A[K+1], or
• Q = A[K] and P = A[K+1].

A non-empty zero-indexed sequence B consisting of M integers is called adjacent in array A if the following conditions hold:

• B = A;
• B[M−1] = A[N−1];
• B[K] and B[K+1] are adjacent in A for 0 ≤ K < M−1.

ShortestAdjSeq

##### Complexity:

time complexity is O(NlogN)

space complexity is O(N)

##### Execution:

This is a graph problem, the shortest adjacent sequence is basically a shortest path in a bidirectional graph.

To calculate the shortest path I am using Breath-first-search or Dijkstra’s algorithm.

I don’t agree with the problem specification of one of the extreme cases such as [1,2,1]. I believe that the shortest path is 3, since the beginning and end are not adjacent. But it seems that Codility expects 1.

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

def bfs_shortest_path(paths, start, end):
q = [(start, 1)]

visited_paths = set()
visited_paths.add(start)

while q:
key, distance = q.pop(0)
new_distance = distance + 1
for path in paths[key]:
if path == end:
return new_distance
elif path not in visited_paths:
visited_paths.add(path)
q.append((path, new_distance))

def solution(A):
if len(A) <= 2:
return len(A)

# I dont agree with this edge case based on the problem statement
if A == A[-1]:
return 1

paths = defaultdict(set)

paths[A].add(A)
paths[A[-1]].add(A[-2])

for i in range(1, len(A)-1):
paths[A[i]].add(A[i-1])
paths[A[i]].add(A[i+1])

return bfs_shortest_path(paths, A, A[-1])
```

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

08/4/20

# HackerRank ‘Connecting Towns’ Solution

##### Short Problem Definition:

Gandalf is travelling from Rohan to Rivendell to meet Frodo but there is no direct route from Rohan (T1) to Rivendell (Tn).

But there are towns T2,T3,T4…Tn-1 such that there are N1 routes from Town T1 to T2, and in general, Ni routes from Ti to Ti+1 for i=1 to n-1 and 0 routes for any other Ti to Tj for j ≠ i+1

Find the total number of routes Gandalf can take to reach Rivendell from Rohan.

Connecting Towns

##### Complexity:

time complexity is O(N)

space complexity is O(1)

##### Execution:

This is a simple combinatorics problem. Even though python ints don’t overflow easily, I added the MOD anyways. The code in GoLang is also available.

##### Solution:
```MOD = 1234567

def main():
t = input()
for _ in xrange(t):
n = input()
arr = map(int, raw_input().split())
routes = 1
for value in arr:
routes = ( routes * value ) % MOD
print routes

if __name__ == '__main__':
main()
```

```func connectingTowns(n int32, routes []int32) int32 {
result := int32(1)
for _, value := range routes {
result = (result*value) % 1234567
}
return result
}
```

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