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.
defcircularArrayRotation(a,k,queries):# Example: For array [1, 2, 3, 4, 5] (n=5):# k=0: [1, 2, 3, 4, 5] (no rotation)# k=1: [5, 1, 2, 3, 4] (rotated right once)# k=2: [4, 5, 1, 2, 3] (rotated right twice)# ...# k=5: [1, 2, 3, 4, 5] (full rotation, back to original)# To rotate efficiently without multiple single shifts:# 1. Calculate the effective rotation offset using modulo arithmetic# (since rotating by n positions brings array back to original)# 2. Split the array at the offset and swap the two parts# Calculate the rotation pointoffset=len(a)-k%len(a)# Perform the rotation by concatenating the two slicesrotated=a[offset:]+a[:offset]# Return the elements at the requested indicesreturn[rotated[q]forqinqueries]
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Circular Array Rotation
You are viewing a single comment's thread. Return to all comments →