Rotate Until Sorted
Python
Hard
3 views
Problem Description
Read n integers in a circle. In one move, rotate left by 1 (first element goes to end). Compute minimum moves to make array non-decreasing. If not possible, output -1.
Input Format
First line n. Second line n integers.
Output Format
One integer moves or -1.
Official Solution
import sys
p=sys.stdin.read().strip().split()
if not p: sys.exit(0)
n=int(p[0])
a=list(map(int,p[1:1+n]))
breaks=0
idx=-1
for i in range(n):
if a[i]>a[(i+1)%n]:
breaks+=1
idx=i
if breaks==0:
sys.stdout.write('0')
elif breaks>1:
sys.stdout.write('-1')
else:
sys.stdout.write(str((idx+1)%n))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!