CyclicRotation - Swift-Studies/codility-lessons GitHub Wiki

Solution

public func solution(_ A : inout [Int], _ K : Int) -> [Int] {
    // 1.
    let shouldNotRotate = A.count == K || K == 0 || A.count == 0

    if shouldNotRotate {
        return A
    }

    // 2.
    let realRotation = K % A.count
    
    // 3.
    let range = 0...(A.count - 1 - realRotation)
    let slice = A[range]

    A.removeSubrange(range)

    // 4.
    return A + firstPick
}

Explanation

  1. First we need to make some validations and check if there is no need to rotate the array. So, we will not have to rotate the array when:

    • The array is empty
    • The number of items is equal to the number of rotations
    • The number of rotations is zero
  2. Now we should discover the** real number of rotations**. The modulus returns the same value as K if K is less than or equal A.count, otherwise, returns the remaining. Once we already checked if the array count is zero, there is no risk of division by zero here.

  3. Given the real number of rotations we should slice the array starting from its startIndex until the number of rotations (-1). The slice operation will save us from using loops.

  4. Finally, we take that slice and append it at the end of the array.

Results

  • Complexity: O(1)