Solution to Cyclic-Rotation by codility

9 Feb


Question Name: Cyclic-Rotation or CyclicRotation

With Python’s syntactic sugar, the solution is pretty short.

Well, kind of too easy. Let’s try a C++ solution to demo the details better.

Thanks to @micropentium6, the original C++ solution is ugly and bad. Please refer to the solution from @micropentium6. Also another Python solution with the same method as @micropentium6’s can be found in an older post.

18 thoughts on “Solution to Cyclic-Rotation by codility

  1. With all due respect, your C++ solution is still like Python tricks. By pushing back, the vector is extended through newly allocated space. You can, actually, do this in place with or without vector.

  2. Javascript Solution

  3. My Javascript solution:

  4. Here is what I came up with for a C# solution. It scored 100% on Codility:

  5. Hello, I am trying to understand your solution and I have to question that I do not find the logic. Please could illustrate me about it or where I can read more details about your code.
    The questions are comment on the solution. Thank you in advances
    def solution(A, K):
    # write your code in Python 2.7
    if len(A) == 0:# why do you equal to cero len(A)?
    return A

    K = K % len(A)# Why do you module K % len(A)
    return A[-K:] + A[:-K]

    • Hello, they are mostly some mathematic issues.
      >> why do you equal to cero len(A)?
      A: handle the special case. Otherwise, when len(A) is 0, “K = K % len(A)” is illegal.

      >> Why do you module K % len(A)
      A: To make sure K is in the range of valid index (between 0 and len(A) – 1). The original question is rotation, so if we increase or decrease K by len(A), the result is totally the same.

  6. My C solution:

  7. My Java solution (100%)

  8. Do we really need to shift array n times ? Instead we only need to figure out what is the index of the array would become the first element of new array, and then copy old array to new array. The following are my java solution.

Leave a Reply

Your email address will not be published. Required fields are marked *