Codility — CyclicRotation — Swift

Muhammad Muizzsuddin
1 min readJul 21, 2020
public func solution(_ A : inout [Int], _ K : Int) -> [Int] {
if A.count == K || K == 0 || A.count == 0 { return A }
let rotation = K % A.count
let range = 0...(A.count - 1 - rotation)
let firstPick = A[range]
A.removeSubrange(range)
return A + firstPick
}

Explanation

Is there any possibility of empty K or empty Array? Yes

Handle if rotation bigger than count? Yes

Is without loop possible? Yes

We want to rotate just by moving elements without loop — O(1) then we can perform modulus operation to K by A.count so that we can build valid range for A. Then to avoid ZeroDivide error, we check if A.count or K is 0.

Why modulus operation? Because if rotation equals A.count it is just same with no rotation at all. So modulus will return remaining rotation.

Total Score

100%

--

--