0

I tried to solve the Circular Array Rotation problem on HackerRank. https://www.hackerrank.com/challenges/circular-array-rotation/problem

The following code passes all test cases except case #4, which gets a runtime error. Could someone point out the problem?

def circularArrayRotation(a, k, queries):

    if k < len(a):
        k = k
    elif k == len(a):
        k = 0
    else:
        k = k%a

    newList = []


    for val in queries:
        newInd = -k+val
        if abs(newInd) > len(a):
            newInd = newInd - (len(a)-1)
            newList += [a[newInd]]
        else:
            newList += [a[newInd]]        


    return newList
3
  • you need to make it fast as it is exceeding the required time limit for that case Commented Jan 21, 2019 at 1:25
  • I don't know how to make it faster Commented Jan 21, 2019 at 2:51
  • Try to get the rotated array at once and in new list store the value of that query index from rotated array Commented Jan 21, 2019 at 2:59

9 Answers 9

4

Your solution is correct. But is not running within that time limit for that case 4 only.

You are calculating the value each time for new queries, which is taking time.

What you can do is take the rotated array at once . and then run the queries on the rotated array. Save the result in the list and return it back.

def circularArrayRotation(a, k, queries):

    new_arr = a[-k%len(a):] + a[:-k%len(a)]
    # list slicing is done here.  it will get the right rotated array 

    result = []
    for i in queries:
        result.append(new_arr[i])
        # running queries on rotated array
    return result

using above method , list slicing is done in o(n) time . and then running the queries is done is o(1) time.

Sign up to request clarification or add additional context in comments.

Comments

1
def circularArrayRotation(a, k, queries):
    j= len(a)

    for x in range(k):
        n=a[j-1]
        a.insert(0,n)
        a.pop(j)

    newList= []

    for m in queries:
        newList.append(a[m])

    return newList

Comments

1
def circularArrayRotation(a, k, queries):
    #rotation
    for _ in range(k):
        a.insert(0, a.pop())
    #putting answer according to query
    ans = []
    for i in queries:
        ans.append(a[i])    
    return ans

1 Comment

While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
0

Well you can use deque A deque is a double-ended queue. It can be used to add or remove elements from both ends.

from collections import deque
    def circularArrayRotation(a, k, queries):
        result=[]
        a = deque(a) 
        a.rotate(k) 
        a = list(a) 

        for v in queries:
            result.append(a[v])

        return(result)

Comments

0

I know this is very old, but I was just solving this, so I figured might as well drop by, your else case is wrong! It should be k = k % len(a), you wrote k % a, now I write c++, so don't know what that even does in python, but I'm pretty sure that doesn't automatically put in len(a) Besides, why are you bothering putting that in if else block just modulo every time, if it's smaller, no value change, for => it fixes it to the right value.

Comments

0

I believe a deque is the approach to go, as AnkushRasgon's and shyamantha's answers. Here I post my version in Java. All tests passed.

static int[] circularArrayRotation(int[] a, int k, int[] queries) {

    LinkedList<Integer> list = Arrays.stream(a).boxed()
            .collect(Collectors.toCollection(LinkedList::new));
    
    for (int i = 0; i < k; i++) {
        list.push(list.pollLast());
    }
    
    for (int i = 0; i < queries.length; i++) {
        if (queries[i] < list.size()) {
            queries[i] = list.get(queries[i]);
        }
    }
    
    return queries;
}

Comments

0
def circularArrayRotation(a, k, queries):
    reverse_a = list(reversed(a))
    reverse_a_copy = reverse_a.copy()
    for x in range(k):
        item = reverse_a[x]
        reverse_a_copy.remove(item)
        reverse_a_copy.append(item)
    line = []
    for x in queries:
        line.append(list(reversed(reverse_a_copy))[x])
    return line

1 Comment

You should always try to provide some explanation when you try to help someone solving a problem, it's much better and appreciated
0
a=[1,2,3,4,5]
s=2
def rotateList(arr,d,n):
  arr[:]=arr[d-1:n]+arr[0:d-1]
  return arr

print(rotateList(a,5,len(a)))

Comments

0
    for i in range(k):
        random_a = len(a)
        random_b = random_a - 1
        random_c = a.pop(random_b)
        a = [random_c] + a
    oz = a
    random_list = []
    for i in queries:
        z = oz[i]
        y = str(z)
        random_list.append(y)
    return random_list```
is this the correct answer


    

1 Comment

Better to give an explanation of your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.