Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codility - Tape equilibrium training using Python

Tags:

python

A non-empty zero-indexed 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.

def solution(A):
N = len(A)
my_list = []
for i in range(1, N):
    first_tape = sum(A[:i - 1]) + A[i]
    second_tape = sum(A[i - 1:]) + A[i]
    difference = abs(first_tape - second_tape)
    my_list.append(difference)
print(min(my_list))
return min(my_list)

My solution gets 100% on Correctness but 0% on Performance. I think it is supposed to be O(N) but my time complexity is O(N*N). Can anyone please give me advice please?

like image 388
Jun Jang Avatar asked Nov 28 '22 10:11

Jun Jang


2 Answers

You can change your code to something like below to have complexity O(N).

def solution(A):          
    s = sum(A)
    m = float('inf')
    left_sum = 0
    for i in A[:-1]:
        left_sum += i
        m = min(abs(s - 2*left_sum), m)
    return m
like image 172
Slouei Avatar answered Dec 14 '22 13:12

Slouei


Functional approach as @darkvalance wrote, but with comments:

from itertools import accumulate

def solution(A):
    array_sum = sum(A)  # saving sum of all elements to have an O(n) complexity

    # accumulate returns accumulated sums
    # e.g. for input: [3, 1, 2, 4] it returns: [3, 4, 6, 10]
    # we are passing a copy of the array without the last element
    # including the last element doesn't make sense, becuase
    # accumulate[A][-1] == array_sum
    accumulated_list = accumulate(A[:-1])

    return min([abs(2*x - array_sum) for x in accumulated_list])
like image 42
TenaciousRaptor Avatar answered Dec 14 '22 12:12

TenaciousRaptor