I just completed a Codility test. The question presented was pretty simple but I may have over thought it.
Question:
Find the element which has the highest absolute deviation from the mean. E.g.
Array = [1,1,-1,1]
.The average is 0.5, so the absolute deviation for each element in the array is[0.5,0.5,1.5,0.5]
(note that the-1.5
goes to1.5
after taking the absolute values of each deviation value) and thus the index with the max absolute deviation is2
(the index starts from0
).
My code was:
def solution(A):
if len(A) > 0:
average = sum(A)*1.0/len(A)
max_avg = 0
pos = 0
for i in range(len(A)):
if abs(A[i] - average) > max_avg:
max_avg = abs(A[i] - average)
pos = i
return pos
else:
return -1
If there's a tie between the max deviation elements i.e. two or more indexes have the same absolute deviation then either of them can be given. The required time-complexity is \$O(N)\$ and space-complexity is \$O(1)\$. In theory, this problem should be really easy but this was my first technical test and I might have overlooked something. Did I possibly miss anything?