Codility – Tape equilibrium training using 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?

Answer

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