Codility

"Algorithms"

Posted by Ping on June 15, 2019
1
%config IPCompleter.greedy=True

Merge sort

Sort an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def split_sort(A):
    if len(A) <= 1:
        return A
    middle_index = int(len(A)/2)
    left = split_sort(A[:middle_index])
    right = split_sort(A[middle_index:])
    return merge(left, right)

def merge(left, right):
    result = []
    i, j = 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result.extend(left[i:])
    result.extend(right[j:])
    return result
B = [1, 2, 3, 4, 5, 6, 7, 90, 21, 23, 45]
A = [-5, 100, 2, 32, 112, -234, 0.5, 111, -90, 23.4, 123]
C = [-9999999999, 2, -2.9, -2.989, 0, 10293432029]

print(split_sort(B))
print(split_sort(A))
print(split_sort(C))
1
2
3
[1, 2, 3, 4, 5, 6, 7, 21, 23, 45, 90]
[-234, -90, -5, 0.5, 2, 23.4, 32, 100, 111, 112, 123]
[-9999999999, -2.989, -2.9, 0, 2, 10293432029]

FrogJmp

A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.

Count the minimal number of jumps that the small frog must perform to reach its target.

Write a function:

def solution(X, Y, D)

that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.

For example, given:

X = 10 Y = 85 D = 30 the function should return 3, because the frog will be positioned as follows:

after the first jump, at position 10 + 30 = 40 after the second jump, at position 10 + 30 + 30 = 70 after the third jump, at position 10 + 30 + 30 + 30 = 100 Write an efficient algorithm for the following assumptions:

X, Y and D are integers within the range [1..1,000,000,000]; X ≤ Y.

1
2
3
4
5
6
7
8
9
def solution(X, Y, D):
    # write your code in Python 3.6
    step = 0
    while X < Y:
        X += D
        step += 1
    return step
result = solution(10, 85, 30)
print(result)
1
3

The following issues have been detected: timeout errors.

For example, for the input (3, 999111321, 7) the solution exceeded the time limit.

Use following code instead:

1
2
3
4
5
6
7
8
9
def solution(X, Y, D):
    # write your code in Python 3.6
    diff = Y - X
    step = diff/D
    if step == int(step):
        return int(step)
    return int(step) + 1
print(solution(10, 85, 30))
print(solution(1, 5, 2))
1
2
3
2

Fibonacci Array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def solution(N):
    # write your code in Python 3.6
    if N < 0:
        print("incorrect!")
    elif N == 0:
        return 0
    elif N == 1:
        return 1
    else:
        return solution(N-1) + solution(N-2)
print(solution(0))
print(solution(1))
print(solution(2))
print(solution(3))
print(solution(20))
1
2
3
4
5
0
1
1
2
6765

BinaryGap

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.

Write a function:

def solution(N)

that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn’t contain a binary gap.

For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation ‘100000’ and thus no binary gaps.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [1..2,147,483,647].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def solution(N):
    # write your code in Python 3.6
    binary = bin(N)[2:]
    s = binary.strip('0')
    max_length = 0
    gap = []
    for i in range(len(s)):
        if s[i] == '0':
            max_length +=1
        else:
            if max_length <1:
                max_length = 0
            else:
                gap.append(max_length)
                max_length = 0
    if len(gap) == 0:
        print(f"Number {N} in binary is {binary}, it has NO gap!")
    else:
        print(f"Number {N} in binary is {binary}, it has {len(gap)} gaps, and the longest gap is {max(gap)}.")


# 529 -> 1000010001
# 5 -> 101
solution(9)
solution(529)
solution(20)
solution(15)
solution(32)
solution(1041)

1
2
3
4
5
6
Number 9 in binary is 1001, it has 1 gaps, and the longest gap is 2.
Number 529 in binary is 1000010001, it has 2 gaps, and the longest gap is 4.
Number 20 in binary is 10100, it has 1 gaps, and the longest gap is 1.
Number 15 in binary is 1111, it has NO gap!
Number 32 in binary is 100000, it has NO gap!
Number 1041 in binary is 10000010001, it has 2 gaps, and the longest gap is 5.

Candidate Report: 100%

OddOccurrencesInArray

A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.

For example, in array A such that:

A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9 the elements at indexes 0 and 2 have value 9, the elements at indexes 1 and 3 have value 3, the elements at indexes 4 and 6 have value 9, the element at index 5 has value 7 and is unpaired. Write a function:

def solution(A)

that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.

For example, given array A such that:

A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9 the function should return 7, as explained in the example above.

1
2
3
4
5
6
7
8
9
import collections

def solution_A(A):
    # write your code in Python 3.6
    counter = dict(collections.Counter(A))
    for key, value in counter.items():
        if value == 1:
            return key
solution_A([1,2,3,6,2,3,1])
1
6

Solution above has higher complexity. However, the bitwise operator can make it O(N) as follows:

1
2
3
4
5
6
7
8
def solution_B(A):
    # Numbers appear twice are counteracted by using n ^ n = 0
    n = 0
    for i in A:
        n ^= i # XOR operator, return 1 when bits are different, otherwise return 0. n ^ n =0, n ^ 0 = n
        
    return n
solution_B([1,2,3,6,2,3,1])
1
6

CyclicRotation

An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place).

The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.

Write a function:

def solution(A, K)

that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.

For example, given

1
2
3
4
5
6
7
8
9
A = [3, 8, 9, 7, 6]
K = 3 the function should return [9, 7, 6, 3, 8]. Three rotations were made:

[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8] For another example, given

A = [0, 0, 0]
K = 1 the function should return [0, 0, 0]

Given

1
2
A = [1, 2, 3, 4]
K = 4 the function should return [1, 2, 3, 4]

Assume that:

N and K are integers within the range [0..100]; each element of array A is an integer within the range [−1,000..1,000].

1
2
a = [3, 8, 9, 7, 6]

1
2
3
4
5
6
7
8
9
def solution_A(A, K):
    # write your code in Python 3.6
    length = len(A)
    if length == 1 or K % length == 0:
        return A
    offset = K % length
    return A[-offset:] +  A[:-offset]
print(solution_A(a, 3))

1
[9, 7, 6, 3, 8]

Solution above gives a mark of 87% because the empty array was not considered and thus could cause an divided by 0 exception.

1
2
3
4
5
6
7
8
9
10
11
12
def solution_B(A, K):
    # For moving leftwards, just give an negative number
    length = len(A)
    if length == 0:
        return A
    offset = K % length
    if offset == 0:
        return A
    return A[-offset:] +  A[:-offset] 
print(solution_B(a, 3))
print(solution_B([],100))
print(solution_B([1,2,3], 300))
1
2
3
[9, 7, 6, 3, 8]
[]
[1, 2, 3]

PermMissingElem

An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.

Your goal is to find that missing element.

Write a function:

def solution(A)

that, given an array A, returns the value of the missing element.

For example, given array A such that:

A[0] = 2 A[1] = 3 A[2] = 1 A[3] = 5 the function should return 4, as it is the missing element.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [0..100,000]; the elements of A are all distinct; each element of array A is an integer within the range [1..(N + 1)].

1
2
3
4
5
6
7
def solution_1(A):
    # write your code in Python 3.6
    length = len(A)
    full_list = list(range(1, length + 2))
    return list(set(full_list) - set(A))[0]

print(solution([1,3,4,5,6]))
1
2
1
2
3
4
5
6
7
8
def solution_2(A):
    # Matematcial solution: A list of successive number's sum is (n * ( n + 1 )) / 2
    full_length = len(A) + 1
    full_list = range(1, full_length + 1)
    sum_full_list = full_length * (full_length + 1) /2
    sum_A = sum(A)
    return int(sum_full_list - sum_A)
print(solution_2([1,3,4,5,6]))  
1
2
1