Codility#

BinaryGap | Level:Easy#

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:

class Solution { public int solution(int 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].

Solution:#

[1]:
check_list= [x for x in range(1,2147)]
# check_list

def solution(N):
    # write your code in Python 3.6
    #Check if N in given range. [1..2,147,483,647]
    global check_list1041
    if N in check_list:
        # converting N to binary format
        binary_format = format(N,'b')
        zero_count_lst = []

        zero_counter= 0
        first_one= False
        second_one= False
        # counting number of zeros in between two 1's
        for char in binary_format:
            if char == '1'and not first_one:

                first_one=True
            if char == '0'  and first_one:
                zero_counter += 1
            # At this stage two actions, if char is 1 and first_one,
            if char == '1'  and first_one:
                zero_count_lst.append(zero_counter)
                zero_counter=0

        if len(zero_count_lst) > 0:
            return max(zero_count_lst)
        else:
            return 0

N = int(input())
solution(N)

ArrayRotation#

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

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

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]. In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.

[8]:
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
n_k_range = 100
#  elem_range -1000 to 1000
def solution(A, K):
    # write your code in Python 3.6
    # Adding checks later for both n_k_range and elem_range.

    B=[]
    n = len(A)
    if n > 100 or K > 100:
        return

    for elem in A:
        if elem < -1000 or elem > 1000:
            return

    for i in range(n):
        # The formula for rotation. For shifting right K times, use i-K.
        A_n = (i-K)%n
        B.append(A[A_n])

    return B
# TODO: Make input of this.
#([3, 8, 9, 7, 6], 2)
[8]:
1

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.

Write an efficient algorithm for the following assumptions:

N is an odd integer within the range [1..1,000,000]; each element of array A is an integer within the range [1..1,000,000,000]; all but one of the values in A occur an even number of times.

[21]:
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
from collections import Counter
def getting_key_from_dict(counter_dict):
    for key,value in counter_dict.items():
        if value == 1:
            return key
        else :return 0
def solution(A):
    # write your code in Python 3.6
    # Defiing checks:
    n=len(A)
    # N should be odd integer
    n_mod = n%2
    if n_mod == 0:
        return
    for elem in A:
        if elem > 1000000000:
            return
    # Calculate counter of elements of A
    # Check if the counter has only one element.
    c = Counter(A)
    counter_dict=dict(c)
    return getting_key_from_dict(counter_dict)

# A = [9, 3, 9, 3, 9, 7, 9]
A=[3, 3, 3, 4, 4, 5, 5]
solution(A)
[21]:
0

FrogJump#

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.

[28]:
# 10, 85, 30 , X, Y, D
import math as m
# def solution(X, Y, D):
#     # Checks
#     limit = 1000000000
#     if X>limit or Y>limit or D>limit or X>Y:
#         return
#     steps = X
#     count = 0
#     while steps < Y:
#         steps = steps + D
#         count+=1
#     return count
def solution(X, Y, D):
    # Checks
    limit = 1000000000
    if X>limit or Y>limit or D>limit or X>Y:
        return
    return m.ceil((Y-X)/D)
solution(1, 5, 2)
[28]:
2

MissingElement#

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:

class Solution { public int solution(int[] 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)].

[51]:
def solution(A):
    # write your code in Python 3.6
    # Defiing checks:
    # Check if N is an integer within the range [0..100,000]
    n=len(A)
    if len(A) == 0:
        return 1

    if n > 100000 :
        return
    # Check if elements of A are all distinct
    if len(set(A)) != n:
        return
    # Check if each element of array A is an integer within the range [1..   (N + 1)].
    for elem in A:
        if elem > n+1 or elem < 1:
            return
    #### APPROACH 1 #####
    # # Sorting array A in ascending order
    # A.sort()

    # for i in range(n):
    #     if A[i] != i+1:
    #         return i+1

    ##### APPROACH2 #####
    # # Using XOR to find the missing number.
    # arr_xor = A[0]
    # for i in range(1,n):
    #     arr_xor = arr_xor ^ A[i]
    # N_xor = 1
    # for i in range(2,n+2):
    #     N_xor = N_xor ^ i
    # return arr_xor ^ N_xor

    ##### APPROACH3 #####
    # Using Sum substraction
    arr_sum = sum(A)
    N_sum = (n+1)*(n+2)//2
    return N_sum - arr_sum


# A=[2, 3, 1, 5]
# A=[1, 3, 6, 4, 2]
# A=[]
solution(A)

[51]:
4

TapeEquilibrium#

A non-empty array A consisting of N integers is given. Array A represents numbers on a tape.

Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], …, A[P − 1] and A[P], A[P + 1], …, A[N − 1].

The difference between the two parts is the value of: |(A[0] + A[1] + … + A[P − 1]) − (A[P] + A[P + 1] + … + A[N − 1])|

In other words, it is the absolute difference between the sum of the first part and the sum of the second part.

For example, consider array A such that:

A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3 We can split this tape in four places:

P = 1, difference = |3 − 10| = 7 P = 2, difference = |4 − 9| = 5 P = 3, difference = |6 − 7| = 1 P = 4, difference = |10 − 3| = 7 Write a function:

def solution(A)

that, given a non-empty array A of N integers, returns the minimal difference that can be achieved.

For example, given:

A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3 the function should return 1, as explained above.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [2..100,000]; each element of array A is an integer within the range [−1,000..1,000].

[65]:
def solution(A):
    n = len(A)
    if n < 1:
        return 0
    if n ==1:
        return abs(A[0])
    for elem in A:
        if elem > 1000 or elem < -1000:
            return
    ### Approach 1 ###
    # sum_l = []
    # for i in range(1,n):
    #     left_sum = sum(A[:i])
    #     right_sum = sum(A[i:])
    #     sum_l.append(abs(left_sum-right_sum))
    # return min(sum_l)
    ### Approach 2 ###
    left = 0
    right = sum(A)
    min_ = None
    for i in range(0,n-1):
        left += A[i]
        right -= A[i]
        if min_ is None:
            min_ = abs(left-right)
        else:
            min_ = min(min_,abs(left-right))
    return min_
A=[3, 1, 2, 4, 3]
solution(A)
[65]:
1