We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
P=[0]*(n+1)# Try to create P that fulfills |P[i] - i| = kforiinrange(1,n+1):ifP[i]==0:# P[i] can be either i+k or i-k.# Greedy approach, try to fit the lexicographically smallest firstifi-k>0andP[i-k]==0:P[i],P[i-k]=i-k,ielifi+k<=nandP[i+k]==0:P[i],P[i+k]=i+k,ielse:# Not possiblereturn[-1]# Skips the first element, added just for better code readabilityreturnP[1:]
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Absolute Permutation
You are viewing a single comment's thread. Return to all comments →
Simple approach in python: