Skip to content

Instantly share code, notes, and snippets.

@MrNocTV
Created July 11, 2017 06:12
Show Gist options
  • Save MrNocTV/a781eef79f67b3ff178beeb30b6db9a4 to your computer and use it in GitHub Desktop.
Save MrNocTV/a781eef79f67b3ff178beeb30b6db9a4 to your computer and use it in GitHub Desktop.
Larry's Array - Check if an array can be sort by rotating 3 consecituve elements (all elements are unique)
'''
Given an array, all elements are unique, you can only perform rotation on 3 consecutive elements:
A B C
Example
A B C -> B C A -> C A B -> A B C
Given an array, find out if it is possible to sort it by only performing rotation.
Solution:
https://www.hackerrank.com/challenges/larrys-array/editorial
Basically, count the inversions in the array.
If it is even, then the array can be sorted
Otheswise, it cant be sorted.
Using the old code for counting inversions using merge sort
'''
def merge_sort(arr, inverse_count):
if len(arr) <= 1:
return arr
# divide into two parts
mid = (len(arr)+1)//2
left = arr[:mid]
right = arr[mid:]
# recursive call on both parts
left = merge_sort(left, inverse_count)
right = merge_sort(right, inverse_count)
# merge and return the result
return merge(left, right, mid, inverse_count)
def merge(left, right, mid, inverse_count):
result = [None]*(len(left) + len(right))
i, j, k = 0, 0, 0
count = 0
# one by one pick smallest elements from left and right
#print(left, right, end = ' ')
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result[k] = left[i]
k += 1
i += 1
else:
result[k] = right[j]
k += 1
j += 1
count += mid - i
# get the rest from left (if any)
while i < len(left):
result[k] = left[i]
k += 1
i += 1
# get the rest from right (if any)
while j < len(right):
result[k] = right[j]
k += 1
j += 1
#print(count)
inverse_count[0] += count
return result
if __name__ == '__main__':
from sys import stdin, stdout
t = int(stdin.readline())
for _ in range(t):
n = int(stdin.readline())
arr = [int(x) for x in stdin.readline().split()]
inversions = [0]
merge_sort(arr, inversions)
inv_count = inversions[0]
print('YES' if inv_count % 2 == 0 else 'NO')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment