Last active
August 29, 2015 13:56
-
-
Save tymofij/9027062 to your computer and use it in GitHub Desktop.
Solution to Array-Inversion-Count by codility
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://codility.com/demo/take-sample-test/array_inversion_count | |
import bisect | |
def solution(A): | |
""" computes the number of inversions in A, or returns -1 if it exceeds 1,000,000,000 | |
""" | |
# the idea is to store elements left of n-th sorted, | |
# which would allow us to easily find the number of them greater than n-th. | |
sorted_left = [] | |
res = 0 | |
for i in xrange(1, len(A)): | |
bisect.insort_left(sorted_left, A[i-1]) | |
# i is also the length of sorted_left | |
res += (i - bisect.bisect(sorted_left, A[i])) | |
if res > 1000000000: | |
return -1 | |
return res | |
assert solution([1, 2]) == 0 | |
assert solution([2, 1]) == 1 | |
assert solution([-1, 6, 3, 4, 7, 4]) == 4 | |
assert solution([]) == 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment