• + 90 comments

    Easy and fast as hell --> O(n) time and O(1) Space........

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        int K = in.nextInt();
        int Q = in.nextInt();
        int rot = K % N;
        int[] arr = new int[N];
        for (int i = 0; i < N; i++)
            arr[i] = in.nextInt();
        for (int i = 0; i < Q; i++) {
            int idx = in.nextInt();
            if (idx - rot >= 0)
                System.out.println(arr[idx - rot]);
            else
                System.out.println(arr[idx - rot + arr.length]);
    		}
    	}
    

    Thanks for the votes guys. I never thought my solution would be on the top of the discussion forums. Anyways here is the mod based solution which many people found useful. Godspeed!

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int k = in.nextInt();
        int q = in.nextInt();
        int[] a = new int[n];
        for(int a_i=0; a_i < n; a_i++){
            a[a_i] = in.nextInt();
        }
        for(int a0 = 0; a0 < q; a0++){
            int m = in.nextInt();
            System.out.println(a[(n - (k % n)+ m) % n]);
        }               
    }
    
    • + 2 comments

      I did something similar, but I used mod in case

      K > arr.lenth + idx.

      • + 3 comments
        [deleted]
        • + 5 comments

          Very easy. Took me only about 1 minute to solve in python. Hackerrank - Circular Array Rotation Solution

          • + 0 comments

            Very Nice !

          • + 0 comments

            congrats smartass

          • + 1 comment

            can u pls tellme what's wrong with my code?

            def circularArrayRotation(a, k, queries):
            b=[]
            l=[]
            n=len(a)
            b=a[n-k:]+a[:n-k]
            for i in (queries):
                c=b[i]
                l.append(c)
            return l
            
            • + 2 comments

              The problem is that k may be greater than n. So you have you write

              k = k%n

              For example, if we have to make k = 6 rotations in a list containing 3 elements.

              It is the same as making 0 rotation. Since every element will be in the

              same position after 6 rotations.

              k%3 = 0 when k=6

              k%3 = 2 when k=5

              2 rotations are the same as making 5 rotations.

              • + 0 comments

                Thank u .

              • + 1 comment

                exactly my point also is the same. no use of rotation further when orginal array and rotated array are same. Could you tell me whether logic will work ?

                static int[] circularArrayRotation(int[] a, int k, int[] queries) { int[] rotationArray = new int[a.Length]; int[] result = new int[queries.Length]; int rotationStartIndex = (a.Length - k); int rotationStopIndex = (a.Length - k) - 1; int index = 0; while (rotationStartIndex <= a.Length -1) { rotationArray[index] = a[rotationStartIndex]; index++; rotationStartIndex++; } rotationStartIndex = index; index = 0; while (index <= rotationStopIndex) { rotationArray[rotationStartIndex] = a[index]; index++; rotationStartIndex++; }

                        for (int i = 0; i < queries.Length; i++)
                        {
                            if (queries[i] < result.Length)
                            {
                                result[i] = rotationArray[queries[i]];
                            }
                        }
                        return result;
                
                    }
                
                • + 1 comment

                  No need to create a new array.

                  You can calculate the originalIndex of the given newIndex and just print a[originalIndex].

                  I'm not a java developer. So I don't know the syntax properly. But the answer will most likely be something like this.

                  static int[] circularArrayRotation(int[] a, int k, int[] queries)
                  
                    {
                      int[] result = new int[queries.length];
                      int l = a.length;
                      int index = 0;
                      k = k%l;
                      for (int i = 0;i<a.length;i++,index++) {
                        int queryIndex = queries[i];
                        int originIndex;
                        if (queryIndex<k) {
                          originIndex = l-k+queryIndex;
                        }
                        else {
                          originIndex = queryIndex-k;
                        }
                        result[index] = a[originIndex];
                      }
                      return result;
                    }
                  
                  • + 0 comments

                    best approach

          • + 0 comments
            return [a[(q-k)%len(a)] for q in queries]
            

            Takes constant time for each query

          • + 0 comments

            how much do you earn from your wordpress blogs??

        • + 0 comments

          here is problem solution in java python c++ c and javascript programming.

          HackerRank Circular Array Rotation problem solution

        • + 0 comments

          Here is my c++ solution, you can watch the explanation here : https://youtu.be/MaT-4dnozJI

          Solution 1 O(n + m) :

          vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
              vector<int> newArray(a.size()), result;
              for(int i = 0; i < a.size(); i++){
                  newArray[(i + k) % a.size()] = a[i];
              }
              for(int i = 0; i < queries.size(); i++) result.push_back(newArray[queries[i]]);
              return result;
          }
          

          Solution 2 O(m) :

          vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
              vector<int> result;
              for(int i = 0; i < queries.size(); i++) {
                  int previousIndex = (queries[i] - k + a.size() * 100000 ) % a.size();
                  result.push_back(a[previousIndex]);
              }
              return result;
          }
          
      • + 1 comment

        same here. I know it's too late to reply :P

    • [deleted]
      + 1 comment

      Ah. I was doing some weird modular arithmetic, which led to funky outcomes for the unknown test cases.

      • + 3 comments
        [deleted]
        • + 7 comments

          In your solution, you could use another modular arithmetic, to ensure the index stays within the boundaries of the array.

          queries.forEach(m => {
              // Modulo to stay inside the boundaries of the array
              console.log(arr[(n+m-k)%n]);
          });
          
          • + 2 comments

            In my solution the index are within the boundaries.

            • + 0 comments

              Thanks a ton Dinesh. Beautiful solution. I initially used brute force without understanding the rotation pattern.

              Learnt something new. Your blog is really good

              Cheers

            • + 15 comments
              #include <map>
              #include <set>
              #include <list>
              #include <cmath>
              #include <ctime>
              #include <deque>
              #include <queue>
              #include <stack>
              #include <string>
              #include <bitset>
              #include <cstdio>
              #include <limits>
              #include <vector>
              #include <climits>
              #include <cstring>
              #include <cstdlib>
              #include <fstream>
              #include <numeric>
              #include <sstream>
              #include <iostream>
              #include <algorithm>
              #include <unordered_map>
              
              using namespace std;
              
              
              int main(){
                  int n;
                  int k;
                  int q;
                  cin >> n >> k >> q;
                  vector<int> a(n);
                  for(int a_i = 0;a_i < n;a_i++){
                     cin >> a[a_i];
                  }
                  
                  for(int i=0;i<k;i++){
                      for(int j=0;j<n;j++){
                          if(j+1!=n)
                          {
                              a[j+1]=a[j];
                              
                          }
                             else
                             {
                                 a[0]=a[n-1];
                             }
                      }
                  }
                  for(int a0 = 0; a0 < q; a0++){
                      int m;
                      cin >> m;
                  cout<<a[m]<<endl;}
                  return 0;
              }
              

              can you plz tell me what is wrong with my code???

              • + 1 comment

                Hi, dk201966. Probably you are facing problems because the order you are doing the changes. If you copy the value from the 1st position to the 2nd one and, after this, you copy the 2nd to the 3rd, at the end you will have all the positions with the 1st value. And don't forget saving the last value before overwriting it! PS: you'll probably face other issues with this challenge...

                • + 0 comments

                  Reverse the loop and make it a[j] = a[j-1]

              • + 1 comment

                Dude please fix your "include"s they seem ugly :)

              • + 1 comment

                The main problem in the code is the order of the for loop used for rotating the elenets in the array. You should store the last element value in some temporary variable..and then use a decreasing counter in the mentioned for loop ..then u can store the value in temporary variable to the first element The error in ur code of overwriting values is eleminated by this code!👍

                • + 6 comments

                  why my code gives wrong answers ...?

                  vector <int> circularArrayRotation(vector <int> a, vector <int> m,int n,int k, int q) 
                  {
                          while(k!=0)
                          {
                              int end=a[n-1];
                              for(int i=n-2;i>=0;i--)
                              {
                                  a[i+1]=a[i];
                              }
                              a[0]=end;
                              k--;
                          }
                          
                      return a;
                  }
                  
                  • + 0 comments

                    you need to return q not a.

                  • + 0 comments

                    you are not supposed to print the whole array a but only the elements at positions in queries

                  • + 1 comment

                    how come!, It's not working???

                    • + 0 comments

                      if you try to interchange the value,t then it does not work,

                  • + 1 comment

                    you are doing the loop thing wrong. Firstly i should be initialized to n-1 , then it should be i>0 . Now a[i+1]=a[i]; is wrong. It should be a[i]=a[i-1] because you are running loop from end and not from starting.

                    • + 1 comment

                      It's the same thing brother

                      He is beginning from the second last index and decrementing progressively, copying the element at that index to the next index, which does the same as your approach - working from the last index through to the second index (which is 1) and copying the value at the preceeding index to the one the counter is at. Both methods perform a right rotation of the array elements from indices 1 to n-1, and both shall work if the value at the last index is stored in another variable and is copied to the first index after each rotation.

                      • + 0 comments

                        maybe at that time it did not seem like that. Its good then

                  • + 0 comments

                    you have to return the value of a[q[i]];

                  • + 0 comments

                    int n=a.length; int brr[]=new int[queries.length]; while(k!=0) { int end=a[n-1]; for(int i=n-1;i>0;i--) { a[i]=a[i-1]; } a[0]=end; k--; } for(int i=0;i }

                    return brr;
                    
              • + 0 comments

                if(j+1!=n-1)

              • + 0 comments

                in your code there is assignment of values....shifting of values is absent..

              • + 0 comments

                hi Change your condition as a[j-1]=a[j]; and j=n-1;j>=0;j-- in for loop

              • + 0 comments

                your code is wrong due to elae statement

              • + 0 comments

                I did the same and realized the values of the elements of the array that you assign later has already replaced the other element in the array. For eg: a[1]=a[0] then a[2]=a[1]=a[0] which is equal to each other

              • + 3 comments
                #include <cmath>
                #include <cstdio>
                #include <vector>
                #include <iostream>
                #include <algorithm>
                using namespace std;
                
                int main() {
                    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
                    int n,k,q,i,s=0,e=0, t=0,b;
                    cin>>n>>k>>q;
                    int a[n];
                    for(i=0;i<n;i++)
                    {
                        cin>>a[i];
                        
                    }
                    
                    k=k%n;
                    
                    s=0,e=n-k-1;
                    while(s<e)
                    {
                       t=a[s];
                        a[s]=a[e];
                        a[e]=t;
                        s++;e--;
                        
                    }
                  
                     s=n-k,e=n-1;
                    while(s<e)
                    {
                       t=a[s];
                        a[s]=a[e];
                        a[e]=t;
                        s++;e--;
                        
                    }
                    
                     s=0,e=n-1;
                    while(s<e)
                    {
                       t=a[s];
                        a[s]=a[e];
                        a[e]=t;
                        s++;e--;
                        
                    }
                    
                     for(i=0;i<q;i++)
                    {
                        cin>>b;
                         cout<<a[b]<<endl;
                        
                    }
                    
                    
                    
                    
                    return 0;
                }
                
                • + 1 comment
                  faster than urs i guess.. happy coding
                  #include<bits/stdc++.h>
                  
                  using namespace std;
                  
                  
                  int main() {
                     long long int k,n,q;
                      cin>>n>>k>>q;
                      k=k%n;
                     long long int i,ar[n],x,s=0;
                      for(i=0;i<n;i++)
                          cin>>ar[i];
                      for(i=1;i<=q;i++)
                      {
                            cin>>x;
                       s=n-k+x;
                       if(s<n)
                           cout<<ar[s]<<endl;
                       else if(s>=n)
                       { s=s-n;
                           cout<<ar[s]<<endl;
                      }}
                  
                      return 0;
                  }
                  
                  • + 0 comments

                    how do u thought about that...??

                • + 0 comments

                  Thank you very much..passed all test cases.

                • + 0 comments

                  int* circularArrayRotation(int a_count, int* a, int k, int queries_count, int* queries, int* result_count) { void reverse(int a[],int,int); int i,j,count,x=0; static int s[100]; reverse(a,x,a_count-k-1); reverse(a,a_count-k,a_count-1); reverse(a,x,a_count-1);

                  for(i=0;i

              • + 2 comments
                #include<bits/stdc++.h>
                
                using namespace std;
                
                
                int main() {
                   long long int k,n,q;
                    cin>>n>>k>>q;
                    k=k%n;
                   long long int i,ar[n],x,s=0;
                    for(i=0;i<n;i++)
                        cin>>ar[i];
                    for(i=1;i<=q;i++)
                    {
                          cin>>x;
                     s=n-k+x;
                     if(s<n)
                         cout<<ar[s]<<endl;
                     else if(s>=n)
                     { s=s-n;
                         cout<<ar[s]<<endl;
                    }}
                
                    return 0;
                }
                

                it will work

                • + 0 comments

                  simpler one:

                  #include <iostream>
                  #include <vector>
                  #include <algorithm>
                  #include <iterator>
                  
                  int main()
                  {
                      int n; std::cin >> n; // array size
                      int k; std::cin >> k; //no of rotations
                      int q; std::cin >> q;
                  
                      std::vector<int> vec;
                      vec.reserve(n);
                      std::copy_n(std::istream_iterator<int>(std::cin), 
                                  n, back_inserter(vec));
                      k %= n;
                      k = n-k;
                      std::rotate(vec.begin(), vec.begin()+k,vec.end());
                  
                      while(q--)
                      {
                          int index; std::cin >> index;
                          std::cout << vec[index]  << std::endl;
                      }
                      return 0;
                  }
                  
                • + 1 comment

                  why are you taking modulus of k???

                  • + 0 comments

                    because after every parent vector's size rotation the array would be same so to save no of times the loop runs. he reduced it

              • + 0 comments

                refer to my code

              • + 1 comment
                #include<bits/stdc++.h>
                
                using namespace std;
                
                
                int main() {
                   long long int k,n,q;
                    cin>>n>>k>>q;
                    k=k%n;
                   long long int i,ar[n],x,s=0;
                    for(i=0;i<n;i++)
                        cin>>ar[i];
                    for(i=1;i<=q;i++)
                    {
                          cin>>x;
                     s=n-k+x;
                     if(s<n)
                         cout<<ar[s]<<endl;
                     else if(s>=n)
                     { s=s-n;
                         cout<<ar[s]<<endl;
                    }}
                
                    return 0;
                }
                

                refer this

              • + 0 comments

                same to you. but if you dry run the code ,then can you understand what is wrong with the code !!

              • + 0 comments

                First, Intialize starting position k= k%2. then,from this first postion (k) use a for loop till (n-1) to assign the values in the new array and finally use another for loop from 0 to (k-1).

                the O(n) of this algorithm is n and it works for all test cases.

                        k=k%n;
                        j=0;
                        for(i=0+k;i<n;i++)
                        {
                            newarr[i]=arr[j];
                            j++;
                        }
                        for(i=0;i<k;i++)
                        {
                            newarr[i]=arr[j];
                            j++;
                        }
                
          • + 1 comment

            it is failing for one case when modulo is used, any help?

            • + 3 comments

              I don't know why you guys are having problem. I have submitted my solution without any problem.

              Anyway if you are having issues than you should upload you code than only i will know what the problem is.

              • + 6 comments

                i actually tried running the code in eclipse, and it is matching the expected output, expect in the last case where it doesnot return the result before enter is pressed, as when the return key is pressed the output becomes fully correct.

                here is my code----------------------

                import java.io.; import java.util.;

                public class Solution {

                public static void main(String[] args) {
                    Scanner s1=new Scanner(System.in);
                    int n=s1.nextInt();
                    int k=s1.nextInt();
                    int q=s1.nextInt();
                    int a[]=new int[n];
                    for(int i=0;i<n;i++)
                        {
                        a[i]=s1.nextInt();
                    }
                    for(int i=0;i<q;i++)
                        {
                        int m=s1.nextInt();
                        System.out.println(a[(n-k+m)%n]);
                    }
                }
                

                }

                • + 0 comments

                  Same problem in another solution.

                • + 1 comment

                  Try this solution it will work

                  • + 2 comments

                    I am not concernerd with the working of the solution, the issue is why is it not working in that particular case, what is the issue? because i am facing the same issue in another problem which is Bigger is Greater in the implementation section.

                    • + 1 comment

                      I can't see any problem in your code. And your code is working fine, though i haven't run it on eclipse but i have tried it on an online compiler and it gave me the correct output.

                      • + 1 comment

                        yes, thats what the problem is , i m not understanding why is it not accepting the solution.

                        Anyways, Thanks for the help

                        • + 1 comment

                          Do this. Had same issue and it fixed it.
                          k=k%n; Looking at the test case found that k is pretty large.

                          • + 0 comments

                            thank you

                • + 0 comments

                  This one is very good but, for the case when k is much more bigger than n it is not working, because an arrayoutofboundException will occure.

                  maybe this will help

                      if (m-k%n < 0) {
                          posValue = m-k%n+n;
                      }
                      else posValue = m-k%n;
                      System.out.println(a[posValue]);
                  
                • + 1 comment

                  Add one line k=k%n; before second loop start then you'll pass all the test.

                  • + 0 comments

                    Thank you

                • + 1 comment

                  i got runtime error by using this

                  • + 1 comment

                    same problem

                    • + 0 comments

                      that's because in test case 4 the number of rotations is much bigger than the number of elements of the array. If you were really executing the rotations, it wouldn't cause any error, but would be very slow, causing errors in other cases (time out). If you use any algorythm that just subtacts the number of rotations from the size of the array, in fact you may try to access elements outside of the array. In case 4 we have an array with 515 elements which is rotated 100000 times. When I try to retrieve the 1st element, the algorythm will try to retriev the element with the index -9485(negative), giving an error of segmentation.

                • + 0 comments

                  What will happen if the rotations(k) arer greater than n. For example

                  There are 3 number of elements i.e n=3 it performs 96 rotations i.e k=96 and m=0 ?

              • + 0 comments

                I posted my code, if u could look at it in the comment section above that would be great!

              • + 0 comments

                include

                using namespace std; int main() { int n,k,q,temp,i,p; cin>>n>>k>>q; int a[n]; for(i=0;i>a[i]; } while(k>0) { temp=a[n-1]; for(i=n-1;i>=0;i--) { a[i]=a[i-1]; } a[0]=temp; k--; for(i=0;i>p; cout<

                return 0;
                

                }

                problem : Terminated due to time out??

          • + 1 comment

            I came up with the exact same solution but "Test case #4" fails with a run time error. I downlowded the input and the output for this test case and ran it locally in Visual Studio (C#) and it does not fail.

            • + 3 comments

              In test case 4 ..it should be noted that the value of k is greater than the no. of elements in the array(n) try using mod operator fr this problem k=k%n;👍

              • + 0 comments

                Helpful!!

              • + 0 comments

                you figured out the time problem bro!!!! great

              • + 0 comments

                Thanks!!

          • + 1 comment

            i tried the same thing but the test case #4 is showing runtime error

            • + 1 comment

              The strange thing is that I uploaded the same solution in C#, C++ and Java 8 and for all of them "Test case #4" fails with a run time error.

              • + 4 comments

                I encountered the same problem. The test case 4 has k bigger than n, which causes segmentation error due to index out of bounds when you do n - k. Solved the problem by setting k = k % n when it is larger than n.

                • + 0 comments

                  Thanks :)

                • + 0 comments

                  Thanks!

                • + 0 comments

                  Thanks!!

                • + 0 comments

                  Thank you a lot. I was stuck in this test case. I thought it was because of a very huge data set that could exceed maximum memory size.

          • + 2 comments

            The "Runtime Error" for test case #4 occurs because k can be much bigger than n and in such cases the code tries to access a negative index.

            For test case 4: k = 100000, n = 515.

            The solution is to apply an extra modulo n on k before substracting:

            queries.forEach(m => {
                // Modulo to stay inside the boundaries of the array
                console.log(arr[(n + m - (k % n)) % n]);
            });
            
          • + 1 comment

            what if array size is 3 and it is rotated 4 times basically n=3 and k=4 and I want value at index = 0

            • + 0 comments

              That is the same as if the array was rotated once. So, at index 0 we'll find the element formerly located at index 1. peace of cake..

        • + 3 comments

          Modular arithmetic is the best way to do this problem. No need to actually rotate the array. Take a look here. Circular Array Rotation

          • + 4 comments

            Python solution using mod:

            ls = [int(x) for x in input().split()]
            n = ls[0]
            k = ls[1]
            queries = ls[2]
            array = [int(x) for x in input().split()]
            result = []
            for q in range(queries):
                q = int(input())
                result.append(array[q-k % n])
            for e in result:
                print(e)
            
            • + 1 comment

              Here is another Python Solution:-

              n,k,q = input().strip().split(' ') n,k,q = [int(n),int(k),int(q)] a = [int(a_temp) for a_temp in input().strip().split(' ')]

              for i in range(q): m = int(input().strip()) print(a[(m-k)%len(a)])

              • + 0 comments

                @hasan2020mainul can you explain the operation a(m-k)%len(a) you did?

            • + 0 comments

              Another simple python solution

              #!/bin/python
              
              import sys
              
              n,k,q = raw_input().strip().split(' ')
              n,k,q = [int(n),int(k),int(q)]
              a = map(int,raw_input().strip().split(' '))
              a = a[n-(k%n):n]+a[0:n-(k%n)]
              for a0 in xrange(q):
                  m = int(raw_input().strip())
                  print a[m]
              
            • + 2 comments

              what is the faster?

              def circularArrayRotation(a, k, queries):
                   a = a[-k:] + a[:-k]
                  return [a[i] for i in queries]

              • + 0 comments

                or we can simply do like this by using python collections

                import collections
                def circularArrayRotation(a, k, queries):
                    d = collections.deque(a)
                    d.rotate(k)
                    return (d[i] for i in queries)
                
              • + 1 comment

                hi @vasilij_kolomie1 your code doesn't work for test case 4

                • + 2 comments

                  Yes when the number of rotations is too big you need to use use rotations mod number of prisoners

                  • + 0 comments
                    def circularArrayRotation(a, k, queries):
                        rotation = k%len(a)
                        a = a[-rotation:] + a[:-rotation]
                        return [a[i] for i in queries]
                    
            • + 0 comments

              nice man...

          • + 3 comments
            def circularArrayRotation(a, k, queries):
                return [a[(val - k) % len(a)] for val in queries]
            
            • + 0 comments

              hello Sir, Will you explain your logic of this problem

            • + 0 comments

              good solution, bad peer )

          • + 0 comments

            right bro. i agree with your point.

        • + 3 comments
          int n;
          int k;
          int q;
          cin >> n >> k >> q;
          int a[n];
          for (int i=0;i<n;i++) cin >> a[i];
          
          int dest=k%n;
          int b[n];
          for (int i=0;i<n;i++) {
              b[dest++]=a[i];
              if (dest==n) dest=0;
          }
          
          for (int i=0;i<q;i++) {
              int m;
              cin >> m;
              cout << b[m] << endl;
          }
          
          • + 0 comments

            Nice solution.. thank you..

          • + 0 comments

            simple python3

            lst=[]
            for i in range(0,k):
                p=a.pop(-1)
                a.insert(0,p)
            for i in queries:
                lst.append(a[i])
            return lst
            
          • + 0 comments

            great logic

    • + 2 comments

      Can you please explain your solution ? why are you taking mod here ?

      • + 2 comments

        he's doing mod caz after n rotation all elements will come at same position as starting point.

        • + 0 comments

          Oh!So that is what it is!I got it!Thanks!

        • + 0 comments

          And this idea will reduce the time ,right?

      • + 1 comment

        Java mod solution:

        for(int i = 0; i < numQueries; i++) {
            System.out.println(array[(arraySize + (in.nextInt() - (numRotations % arraySize))) % arraySize]);
        }
        
        • + 1 comment

          JS Solution

          function circularArrayRotation(a, k, queries) {
              
              for(let i=0;i<k;i++){
                  a.unshift(a.pop());
              }
              return queries.map(q=>a[q]);
          }
          
          • + 0 comments

            Brilliant !!

    • + 1 comment

      Failed for one test case.

      • + 2 comments

        Test case 4? Segmentation fault?

        • + 1 comment

          Yes

          • + 3 comments

            Here's what worked for me in C++. After taking values of n and k:

            while(k greater than n)k=k-n;

            The value of k can be several times greater than n, so by putting this can lead to referencing an index in the array greater than n, which causes segmentation fault. And the output will be correct because performing 5 rotations in an array of 4 elements is same as performing 1 rotation.

            • + 2 comments

              you could use k=k%n, what if the k is doulble or trible the size of n. subtraction always reduce one rotation.

              Consider if k = 3n => k = 3n -n => k = 2n. but in case of modular it reduces to n rotation. k = 3n => k = 3n%n => k = 0.

              • + 1 comment

                If K=2n then the loop will run twice and k will be set to 0. If k is a multiple of n then the array after k rotations will be same as initial array. k=k%n could also do the trick.

                • + 1 comment

                  if k is a multiple of n then won't the remainder be 0?

                  • + 0 comments

                    Yes. Which means, in effect, that no rotation should be performed upon the array, because rotating each element by k will have each of them end up right back where they started. Using 0 for k will have that effect.

              • + 0 comments

                thank you sir.

            • + 1 comment

              This helped me out thanks

              • + 2 comments

                how it worked please can u explain me??

                • + 1 comment

                  You can determine where in the array each element will end up with a simple calculation using the number of elements (n), the number of times you perform the operation (k), and an incrementing variable (use a for loop). Try to figure out the equation and use that answer as the array assignment. You need to use the while loop right before the array assignment because sometimes the calculation you perform will leave you with an array assignment value that is greater (hint) than the amount of array values so you just repeat the same equation until you get a valid value (something < n).

                  • + 0 comments

                    (Y)

                • + 0 comments

                  Here i have explained it in detail. Circular Array Rotation

            • + 0 comments

              Thanks, It worked in Python. In fact, it would work in any language.

        • + 7 comments
          int n,k,q,temp,m,z;
          cin>>n>>k>>q;
          
          int a[n];
          
          for(int x=0;x<n;x++)
          {
              cin>>a[x];
          }
          
          k=k%n;
          for(int y=0;y<k;y++)
          {
             temp = a[n-1];
          
             for(int q=n-1;q>=1;q--)
             {
                 a[q]=a[q-1];
             }
          
              a[0]=temp;
          }
          for(int u=0;u<q;u++)
          {
             cin>>m;
             cout<<a[m]<<endl;                
          }
          

          "Terminated due to timed out" on Case 5,12,13,14 ... help please .. Thanks !

          • + 1 comment

            try to solve in O(n).

          • + 1 comment

            I was using the nested loop algo, was getting timed out. Then i used this (JAVA) Collections.rotate(Arrays.asList(array_name), k);

            i am a beginner, can anyone tell me is this a bad way to solve a problem, if yes why?

            • + 0 comments

              The Actual vision of the problem is to solve it by without actually making any rotations.because rotation takes more time and space.thats why you may get timeout errors if you try to solve it by rotations .we gotta have to solve it by doing calculations .Example: write a simple logic to determine what will be the output after k rotations.if K is equal to N then no rotations needed coz the array will be the same as original after rotations.

          • + 0 comments

            hey ,,if u got the solution of your code please inform me also...thanxx;

          • + 1 comment

            No need to rotate the array you can do this problem much faster. Take a look here, i have explained it in detail. Circular Array Rotation

            Hope it helped you

            • + 1 comment

              hi @Dinesh1306, I tried your solution, but I get this error when I try for large inputs as given in test cases: Sorry, we can't accept your submission. The custom input size should not exceed 50Kb.

              • + 1 comment

                hi @poon12, the solution is working fine, you must have done something wrong. Can you post your code here so that i can check.

                • + 0 comments

                  hi @Dinesh1306 your solution got accepted. thanks :) but yes when i try the solution with large inputs, it gives me that custom input size error.

          • + 2 comments

            Same for me :/ someone please help

            int main() { int n,k,q,r=0; cin >>n>>k>>q;

            int b[n];
            int m[q];
            for (int i=0;i<n;i++)
               {
                cin >> b[i];
               }
            for (int i=0;i<q;i++)
                {
                 cin >> m[i];
                }
            for (int i=0;i<k;i++)
                {
                    r=b[n-1];
                for(int j=n-1;j>0;j--)
                    {
                      b[j]=b[j-1];
                    }
                    b[0]=r;
                }
             for(int i=0;i<q;i++)
               {
                   cout << b[m[i]]<<endl;
               }
            return 0;
            

            }

            • + 2 comments

              Check this

              • + 0 comments
                int main() {
                   long int n; 
                   long  int k; 
                    long  int q,i,t; 
                    scanf("%li %li %li", &n, &k, &q);
                    long int a [n];
                    for (long int a_i = 0; a_i < n; a_i++) {
                       scanf("%li",&a[a_i]);
                    }
                    long int *m = malloc(sizeof(long int) * q);
                    for (long int m_i = 0; m_i < q; m_i++) {
                       scanf("%li",&m[m_i]);
                    }
                   long int b[n];
                    for(i=0;i<n;i++){
                        t=i+k;
                      t=t%n;
                        b[t]=a[i];
                        
                    }
                     for (long  int m_i = 0; m_i < q; m_i++) {
                         printf("%ld\n",b[m[m_i]]);
                     }
                    return 0;
                }
                
              • + 0 comments

                can you give that link it is not opening.

          • + 0 comments

            You can make another array and use modular arithematic approach to insert values in that array. In this way you will solve it in O(n) and there will be no timeout errors :D

          • + 0 comments

            i used this code insted of the second for:

            rotate(a.begin(),a.end()-k,a.end());
            
    • + 7 comments

      What's the space and time efficiency for this code?

      n, k, m = map(int, input().strip().split())
      arr = list(map(int, input().strip().split()))
      k %= n
      arr = arr[-k:] + arr[:-k]
      for i in range(m):
          print(arr[int(input().strip())])
      
      • + 0 comments

        wow!!! fast and easy way to done the problem..

      • + 0 comments

        Thank you!

        Now I know %=

      • + 0 comments

        Really great solution!

      • + 1 comment

        Thanks polmki99! Very clever implementation.

        Here it is in Javascript for those interested.

        function processData(input) {
            //Enter your code here
            var inputList = input.split('\n');
            var details = inputList[0].split(" ");
            var arrayIdx = inputList.slice(2);
            var targetArray = inputList[1].split(" ");
            
            var k = details[1]%details[0];
            
            targetArray = [].concat(targetArray.slice(-k),targetArray.slice(0,-k));
            
            arrayIdx.map(function(elem){return console.log(targetArray[elem]);});
        }
        
        • + 2 comments

          Nice one liner using the built in functions! Unfortunately, this still fails when k is higher than n (test case #4). You seem to be getting around it by overwriting k with:

          var k = details[1]%details[0];
          

          I'm curious to see if there are other, more algorithmic solutions to this in Javascript.

          • + 1 comment

            This works in Javascript for all test cases:

            function main() {
                var n_temp = readLine().split(' ');
                var n = parseInt(n_temp[0]);
                var k = parseInt(n_temp[1]);
                var q = parseInt(n_temp[2]);
              
                a = readLine().split(' ');
                a = a.map(Number);
              
                for (var i=0; i<q; i++) {
                  var m = readLine();
                  console.log(a.slice(m-k%n)[0]);
                }
            }
            
            • + 3 comments

              when i ran my code only sample test cleared and rest failed

              function circularArrayRotation(a, k, queries) { 
              
                  var res = [];
                  var resind = 0;
              
                  while (k > 0) {
                      rotateArr();
                      k--;
                  }
              
                  function rotateArr() {
                      var i = 0;
                      var lastel = a[a.length - 1];
                      var temp1 = a[0];
                      var temp2;
              
                      while (i < a.length-1) {
                          temp2 = a[i + 1];
                          a[i + 1] = temp1;
                          temp1 = temp2;
                          i++;
                      }
              
                      a[0] = lastel;
                  }
              
                  for(var j in queries) {
                      res[resind] = a[j];
                      resind++;
                  }
              
                  return res;
              		}
              
                  I think some issue is in how i am returning the values, please help identify the error
              
              • + 2 comments

                found out what the problem was, new JS code:

                function circularArrayRotation(a, k, queries) {
                
                    var rarr = [];
                    var aind = [];
                    var res = [];
                
                    for (var i = 0; i < a.length; i++){
                        if ((i + k) < a.length) {
                            aind[i] = i + k;
                        } else {
                            aind[i] = (i + k) % a.length;
                        }
                    }
                
                    for (var j = 0; j < a.length; j++) {
                        rarr[aind[j]] = a[j];
                    }
                
                
                    for (var k = 0; k < queries.length; k++){
                        res[k] = rarr[queries[k]];
                    }
                
                    return (res);
                }
                
                • + 0 comments

                  Hi, could you please explain what is happening here? Thanks

                • + 0 comments

                  please explain what is going on in the code

              • + 0 comments

                function circularArrayRotation(a, k, queries) { // Write your code here return queries.map(value => a.reduce((target, item, index) => { let focus = (index + k) % a.length; target[focus] = item; return target; }, [])[value]); }

          • + 1 comment

            More algorithmic? - I don't see any reason to mutate the arrays at all, if all you need is the correct indexes from the rotated input. This just plucks the relevant items from the (rotated) indexes in the query:

            function circularArrayRotation(a, k, queries) {
                let offset = a.length - (k % a.length);
                return queries.map( e => a[(e+offset)%a.length]);
            }
            
            • + 1 comment

              Ah,thanks I got it.. It's all about algorithmic complexity.

              • + 0 comments

                This is O(n) where n is the length of the queries array. It is independent of the length of the input array, since it grabs the input array elements by index and only has to loop through the queries to grab each one.

      • + 0 comments

        how about my solution is it good..

        n,k,q = list(map(int, input().strip().split()))
        a = list(map(int, input().strip().split()))
        a = a[n-(k%n):]+a[0:n-(k%n)]
        [print(a[int(input())]) for _ in range(q)]
        
    • + 0 comments

      Wow! Lovely Solution.. But what if the direction of rotation is left?

      I have given it a try, please let me know if I am wrong:

      if(idx+rot <= arr.length) System.out.println(arr[idx+rot]); else System.out.println(arr[arr.length-(idx+rot)]);

    • + 1 comment

      no Rotation but still does the job :v CHECK THIS out c++ lovers

      im noob in coding so i wrote it so big :(

       int b,n,k,q,ans=0;
      cin>>n>>k>>q;
      int a[n];
      for(int i=0;i<n;i++)
          cin>>a[i];
          if(k==n){
              for(int i=0;i<q;i++)
          {
           cin>>b;
           cout<<a[b]<<endl;
          }
          }
          else if(k>n)
          { while(k>n)
              k=k-n;
              for(int i=0;i<q;i++)
              {
                  ans=n-k;
                  cin>>b;
                  ans+=b;
                  if(ans>n-1)
                      ans-=n;
                  cout<<a[ans]<<endl;
              }
          } else if(k<n)
              {
      
                 for(int i=0;i<q;i++)
              {
                  ans=n-k;
                  cin>>b;
                  ans+=b;
                  if(ans> n-1)
                      ans-=n;
                  cout<<a[ans]<<endl;
              }
              }
      return 0;
      

      }

      • + 0 comments

        smart one more way u could have actually stored rotated version of array while taking array input.

    • + 1 comment

      Very elegant solution!

      (\(\
      (=':')
      (,(")(")
      
      • + 0 comments

        bunny?

    • + 1 comment

      You can further reduce the time. No need to rotate the array just apply simple logic and you can do it in O(1) complexity per query. Check this solution Circular Array Rotation

      • + 0 comments

        Query will be O(1) time complexity regardless of the implementation or correctness since you are accessing an indexed array. Your solution did not make accessing more efficient anymore than it is, but since you are inserting into an array in O(n) time and correctly accessing it passes all tests.

    • + 0 comments

      Thanks buddy!

    • + 1 comment

      How is that O(1) space? You're using an n element array.

      • + 1 comment

        It is O(1) per query. This problem can be solved without actually rotating the array.

        Here is my solution Circular Array Rotation

        • + 1 comment

          Yeah, my bad. It's O(1) per query, but an O(n) space complexity algorithm in the end.

          • + 1 comment

            No,the algorithmn(which is the main part)is of O(1) time complexity you cannot optimize it any further. Space complexity is also optimized you cannot avoid using an array as the problem is based on it.

            • + 1 comment

              You cannot say that. And you cannot call it O(1),

              For example if a problem asks us to sum up all numbers in an array, we can simply take an input and add it to a variable sum, or we can take all inputs in an array. What you just said implies that we cannot distinguish between these 2 algorithms, but we can(One is O(1), other is O(n).

              Of course it isn't sensible to assume that we can solve this problem without the array in this particular case, but I still think that O(1) complexity is wrong.

              • + 1 comment

                Again you misunderstood what i am saying. I am saying that the algorithmn part(i.e. the if and else statment) is O(1) not the whole code, since in this problem we cannot run away from array. And i am claming that my solution is the most optimized one.

                And BTW the example that you gave has O(n)time complexity not O(1) since for ever new element you are doing a computational opperation(i.e. adding the sum and the new input)

                • + 1 comment

                  I'm talking about space complexity. The space complexity is not O(1), and the space complexities in my 2 examples were different(one is O(n) as we are using a WHOLE n element array, while in the other we're using one variable).

                  You on the other hand, are talking about the time complexity. It is O(1) per query and that's correct. But how is space in any way O(1) ? There exists an n element array.

                  • + 1 comment

                    Seems like we missunderstood each other. I was talking about time complexity the whole time. As for the space complexity yes it is O(n), O(1) is not possible in this problem since we have to store the elements.

                    • + 1 comment

                      hi bro,i am a beginner.How to understand these concepts of time complexity and space complexity.

                      • + 1 comment

                        You should not worry about these things if you are a beginner,but since you have asked i have explained it here, take a look. In the beginning your focus should be to complete the task without worrying about these time/space complexities.

                        • + 1 comment

                          thanku :)

                          • + 0 comments

                            My pleasure :)

    • + 0 comments

      Actually, you can do it in O(1) and O(1) space by simply using modulo.

    • + 1 comment
      n,k,q=raw_input().split()
      n,k,q=[int(n),int(k),int(q)]
      s=raw_input()
      s=map(int,s.split())
      while(q!=0):
          m=input()
          print s[(m-k)%n]
          q=q-1
      

      bitch plz python rules

      • + 1 comment

        I really like this one Zeus! I tried to make it more compact:

        n, k, q =   map(int, input().strip().split())
        a       =   [int(i) for i in input().strip().split(' ')]
        for i in range(q):
            m   =   int(input())    
            print(a[(m-k)%n])
        
        • + 0 comments

          and if you wanted to make it really compact..

          n,k,q = list(map(int, input().split()))
          a = list(map(int, input().split()))
          print(*(a[(int(input())-k)%n] for _ in range(q)),sep='\n')
          
    • + 1 comment
      n,k,q=raw_input().split()
      n,k,q=[int(n),int(k),int(q)]
      s=raw_input()
      s=map(int,s.split())
      while(q!=0):
          m=input()
          print s[(m-k)%n]
          q=q-1
      

      bitch plz python rules

      • + 0 comments

        Yeah, it does

        a,arr = [map(int,raw_input().split()) for _ in range(2)] for _ in range(a[2]): print (arr[-(a[1]%a[0]):] + arr[:-(a[1]%a[0])])[input()]

    • + 0 comments

      so good I could cry

    • + 0 comments

      Wow!It is so effective compared to mine

    • + 0 comments

      awsome

    • + 1 comment

      @piyush121 I would like to understand what you did with the modulo operation and how does rot help us in solving thiis code. I am beginner so please be patient and help me.

      • + 0 comments

        Visit here. I have explained it in detail.

    • + 0 comments

      I was faithfully doing a for loop for 1 rotation inside a dummy for loop to have k rotations. Then another for loop to output the m'th position. It worked, but O(n) became n*k; too long for 6 test cases. This comment inspired me to use modulus by n and only print the mth position numbers. I tried to understand it in my own way and shorten your code to:

      System.out.println(a[(m-k+n)%n]);
      
    • + 0 comments

      Could you please explain why time complexiety is O(N) instead of O(Q)?

    • + 0 comments

      Hi piyush can you explain the math behind your solution that would be great

    • + 0 comments

      This can be easily done with a one liner O(1) time and O(1) space

      cout << a[(n+(m-k)%n)%n] << endl;

    • + 0 comments

      You don't need to use extra variable "rot". One can overwrite K with K%N if K is larger than N. Also, there is no need to call arr.length because you already have N.

    • + 1 comment

      This is pretty much more elegant than my solution of using a queue, but a question that I'm having is why use k%n? Can someone please explain this logic?

      Tx

      • + 0 comments

        Because when the number of rotations(k) equals the size of the array(n), the array returns to it's original setup. For example, after 3 rotations, this array is back to original:

        [1,2,3] 0 original
        [3,1,2] 1 rotation
        [2,3,1] 2 rotations
        [1,2,3] 3 rotations //Back to original setup
        [3,1,2] 4 rotations // same as 1 rotation
        

        Therefore if you have 4 rotations, then 4 % 3 is 1, so you will get the same result as if you only had 1 rotation to begin with.

    • + 0 comments

      good catch on the k which can be bigger than the number of elements!!

    • + 1 comment

      Can you guys explain to me this line

      if(idx-rot>=0)
                    System.out.println(arr[idx-rot]);
                 else
                  System.out.println(arr[idx-rot+arr.length]);
      

      I don't understand why it can refer to the roation element of array?

      • + 0 comments

        It's just because in the '(rot-1)th' elements of the array you will have negative indexes, causing errors or, even, segmentation error (as in test case 4). So, doing this, you add N to negative indexes to retrive the correct values from the former array, without rotating it at all.

    • + 0 comments

      arr.unshift(arr.pop())

    • + 1 comment

      Can anyone explain this easily from start ?

      • + 2 comments

        Well, let's try explain using an example case:

        If I have an array(a) with, let's say, N=5 elements: a0=0, a1=1, a2=2, a3=3 and a4=4.
        Let's consider that I have to rotate this array K=6 times.

        So:
        a0={0, 1, 2, 3, 4} (initial array)

        When I right-rotate 6 times this array, following the rules estipulated in this problem, I'll get this:

        a1={4, 0, 1, 2, 3} (1st rotation)
        a2={3, 4, 0, 1, 2} (2nd rotation)
        a3={2, 3, 4, 0, 1} (3th rotation)
        a4={1, 2, 3, 4, 0} (4th rotation)
        a5={0, 1, 2, 3, 4} (5th rotation)
        a6={4, 0, 1, 2, 3} (6th rotation)

        Observe that at the 5th rotation, we got the original array again (a5 == a0). In fact, at every N rotations we'll get the original array. So, we don't need to rotate the array K times if K is greater than N. We can just rotate it (K%N) times (rest of integer division, or just 'modulo operation'). In my example 6%5 = 1.

        And, even in this case, I don't need to actually rotate the array, but just retrieve an element from the array whose position is 1 lower than it was in the original array.
        WHAT???
        Yes, let's consider the initial array and after 1 or 6 rotations, as follows:
        a0={0, 1, 2, 3, 4}
        a1={4, 0, 1, 2, 3} (1st and 6th rotation)

        If I try to retrieve the:
        - 4th element, I'll get 3;
        - 3rd element, I'll get 2, and so on.
        Thus, if I subtract the number of rotations(K) from the index of the element, I'll get its value after K rotations, correct?
        YES and NO!!!
        a1[4] == a0[3]
        a1[3] == a0[2]

        Hummm... aK[m] == a0[m-(k%N)]! Great. No rotation is necessary, but just a simple calculation...
        Let's continue...

        a1[2] == a0[1]
        a1[1] == a0[0]
        a1[0] == a0[-1] OPS! There's no a[-1]!!!

        Here we get an error type "Index out of bounds". It's because we are trying to acces memory positions that are out of the array's boundaries. Probably, it is being used by another variable. A "Segmentation error" message may appear when K is much bigger than N (something like k=100000 and n=515, as in test case 4). It's because we are trying to acces memory positions that are out of the program boundaries and, probably, are being used by another application.

        To correct these errors, we can use the same solution we used to simulate the K>N rotations: modulo operation!
        The answer would be like this:
        aK[m] == a0[(m+N-(K%N))%N].

        We add N to the index to assure it will never be negative.

        Tricky, fast and easy.
        Try implementing this in your application.

        I hope be helpful ;-)

        • + 1 comment

          Sorry, but in this line

          aK[m] == a0[(m+N-(K%N))%N].

          you %N again after +N for what purpose? If i think correctly, it's for rotate again the m index?

          • + 0 comments

            That extra %N was added so that if our ans turns out to be greater than the number of elements in the array , the indexing should again start from index '0'. eg. for m=1, our the later formula without using %N will result to 5. but our ans should be equal to 0 and not 5 thats why we do modulus. so that it could become 0

        • + 0 comments

          Best Approach ever! Hats off!

    • + 0 comments

      Wow, its crazy to see how yours is so similar yet so different from my code. I instead placed the integer at the index it was going to be at from the very beginning

      public static void main(String[] args) {
              Scanner in = new Scanner(System.in);
              int n = in.nextInt();
              int cycles = in.nextInt();
              int queries = in.nextInt();
              int[] a = new int[n];
              for(int a_i=0; a_i < n; a_i++){
                  a[(a_i+cycles) % n] = in.nextInt();
              }
              for(int a0 = 0; a0 < queries; a0++){
                  int m = in.nextInt();
                  System.out.println(a[m]);
              }
          }
      
    • + 0 comments

      does it work in *4*th case?

    • + 0 comments

      Can Someone Explain me Logic Behind it pls

    • + 0 comments

      Thank you!!

    • + 0 comments

      thanks man, its awesome. :)

    • + 0 comments

      i got "Segmentation Fault". Why?

    • + 0 comments

      if (idx - rot >= 0) System.out.println(arr[idx - rot]); else System.out.println(arr[idx - rot + arr.length]); } will u plz make me understand ur logic?? how did it come to ur mind?

    • + 0 comments

      It's O(1) time(for each query) and O(n) space, not the other way around.

    • + 0 comments

      Can somebody please explain the logic ? I did it with loop for shifting array elements but it shows timeout error for large testcases.

    • + 0 comments

      Please explain for me why use a[(n-(k%n) +m) %n]?

    • + 0 comments

      can you please describe this to me:(a[(n - (k % n)+ m) % n])?

    • + 0 comments

      Just wanted to ask how do you came up with the one line solution to the problem.

      System.out.println(a[(n - (k % n)+ m) % n]);
      
    • + 0 comments

      why do we have to use (k%n) instead of just k i.e. (n-k+m)? All TCs except for TC#4 succeed with k.

    • + 0 comments

      Whats the logic? Could you please explain it..

    • + 0 comments

      why my code gives wrong answers ...?

      vector <int> circularArrayRotation(vector <int> a, vector <int> m,int n,int k, int q) 
      {
              while(k!=0)
              {
                  int end=a[n-1];
                  for(int i=n-2;i>=0;i--)
                  {
                      a[i+1]=a[i];
                  }
                  a[0]=end;
                  k--;
              }
              
          return a;
      }
      
    • + 0 comments

      so, if you change the whole format of main method then how will it take the auto generated test cases?

    • + 0 comments

      what if the rotation was in left direction ?

    • + 0 comments

      Can you please explain, how did you find the solution?

    • + 0 comments

      shouldnt you circulate the whole array instead of manipulating the indexes to find the answer.

    • + 0 comments

      O(m) time and O(1) space.

      def circularArrayRotation(a, k, queries):
          return [a[((len(a) - (k % len(a)))+q)%len(a)] for q in queries]
      

      With Love, Python

    • + 0 comments

      where are you rotating the array?

    • + 0 comments

      u did amazing job...what i do...i cirular shift the whole array...can you suggest me the way...when you see a problem like this.

    • + 0 comments

      Nice one!
      Here is my code in C.

      #include <stdio.h>
      #include <stdlib.h>
      
      
      int main(){
          int n,k,q;
          scanf("%d %d %d",&n,&k,&q);
          int a[100000],m,i = 0;
          
          while(i < n)
              scanf("%d",&a[(i++ + k) % n]); 
          
          while(q--){
              scanf("%d",&m);
              printf("%d\n",a[m]);
          }
          return 0;
      }
      

      Position resulting because of rotation is computed first using ((i++ + k) % n).Then the array elements are stored in these positions in the read ing stage itself using scanf() . Suggestions are welcome!

    • + 0 comments

      Why am I getting this error when I have not even touched main() ?

      Here's my function code

      int i,j,arr[queries_count];
      *result_count=queries_count;
      k = k % a_count;
      for(i=1;i<=queries_count;i++)
      {
          j=queries[i]-k;
          if(j<0)
              arr[i]=a[a_count+j];
          else
              arr[i]=a[j];
      }
      return arr;
      

      }

      Segmentation Fault Error (stderr)

      GDB trace: Reading symbols from solution...done. [New LWP 2592] Core was generated by `solution'. Program terminated with signal SIGSEGV, Segmentation fault.

      0 fprintf (__fmt=0x400cc4 "%d", __stream=0x155d010)

      at /usr/include/x86_64-linux-gnu/bits/stdio2.h:97
      

      97 return __fprintf_chk (__stream, __USE_FORTIFY_LEVEL - 1, __fmt,

      0 fprintf (__fmt=0x400cc4 "%d", __stream=0x155d010)

      at /usr/include/x86_64-linux-gnu/bits/stdio2.h:97
      

      1 main () at solution.c:97

    • + 0 comments

      Can anyone explain the maths behind this solution?

    • + 0 comments

      python 3 https://www.hackerrank.com/challenges/circular-array-rotation/forum/comments/514048

    • + 1 comment

      sir can you please help me.Whats wrong with my code ??

      import java.io.; import java.math.; import java.security.; import java.text.; import java.util.; import java.util.concurrent.; import java.util.regex.*;

      public class Solution {

      // Complete the circularArrayRotation function below.
      static int[] circularArrayRotation(int[] a, int k, int[] queries) {
          int last=a[a.length-1];
          for(int i=a.length-2;i>=0;i--)
          {
              a[i+1]=a[i];
          }
          a[0]=a[last];
          for(int i=0;i<queries.length;i++)
          {
              int c=queries[i];
              int m=a[c];
              return m;
              break;
          }
      
      
      }
      
      private static final Scanner scanner = new Scanner(System.in);
      
      public static void main(String[] args) throws IOException {
          BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
      
          String[] nkq = scanner.nextLine().split(" ");
      
          int n = Integer.parseInt(nkq[0]);
      
          int k = Integer.parseInt(nkq[1]);
      
          int q = Integer.parseInt(nkq[2]);
      
          int[] a = new int[n];
      
          String[] aItems = scanner.nextLine().split(" ");
          scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
      
          for (int i = 0; i < n; i++) {
              int aItem = Integer.parseInt(aItems[i]);
              a[i] = aItem;
          }
      
          int[] queries = new int[q];
      
          for (int i = 0; i < q; i++) {
              int queriesItem = scanner.nextInt();
              scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
              queries[i] = queriesItem;
          }
      
          int[] result = circularArrayRotation(a, k, queries);
      
          for (int i = 0; i < result.length; i++) {
              bufferedWriter.write(String.valueOf(result[i]));
      
              if (i != result.length - 1) {
                  bufferedWriter.write("\n");
              }
          }
      
          bufferedWriter.newLine();
      
          bufferedWriter.close();
      
          scanner.close();
      }
      

      }

      • + 0 comments

        hi @1634810124_coe3b you have not used the k variable and also you have wrote a[0]=a[last]; do not assign like this ..because you are using a[0] in the loop afterwards. Tip-->Assign the values in a[0] using temporary variable. since you are using 2 for loops and probably you need one while loop or nested for loop for this kind of approach ...so you may face timeout in some testcases. good luck

    • + 0 comments

      It's for C (''Godspeed!")

      #include <stdio.h>
      
      int main() {
      	
        int n, k, m, mx;
        scanf("%d %d %d", &n, &k, &m);
        int nums[n];
        for (int i = 0; i < n; i++)
          scanf("%d", &nums[i]);
        while (m--) {
          scanf("%d", &mx);
          printf("%d\n", nums[(n + mx - (k % n)) % n]);
        }
        return 0;
      }
      
    • + 0 comments

      what this line is doing "arr[i] = in.nextInt();"

    • + 0 comments

      Wow. The core of the solution is two lines in Ruby (or one line if you don't mind calling a.length three times).

      len = a.length
      queries.collect { |i| a[((len - k) % len + i) % len] }
      

      It may be possible to simplify my expression, but I wasn't able to see how to reduce it.

    • + 0 comments

      gr8 plz send your all the solutions in the discussion section thnks bro

    • + 0 comments
      for(int i=0;i<q;i++){
              int x;
              cin>>x;
              cout<<a[x]<<endl;
          }
      

      why is it saying subscripted value is not an array,vector or pointer...

    • + 0 comments

      Thanks

    • + 0 comments

      Nice solution.. Need to By heart this formula..

    • + 0 comments

      a[(n - (k % n)+ m) % n]

      can u elaborate how this idea come to ur brain

    • + 1 comment

      @piyush121 Please explain above both codes.

      • + 1 comment

        i played with indexes ..

        • + 0 comments

          1first reverse the first half (n-roation) and then reverse next half(the size of rotion rt) - do it one by one ....and at last then reverse the whole arry..

          you just need to pass the indices in reverse function..the code is written

    • + 0 comments

      PLEASE TELL ERROR IN THIS CODE, IT IS SHOWING RUN TIME ERROR

      int main() { long long int n,k,q,a[n],i,m[q],t;

      cin>>n>>k>>q;
      for(i=0;i<n;i++){
          cin>>a[i];
      }
      for(i=0;i<q;i++){
          cin>>m[i]; 
      }
      for(i=0;i<k;i++){
          t=a[n-1];
          for(i=n-2;i>0;i--){
              a[i+1]=a[i];
          }
          a[0]=t;
      }
      for(i=0;i<q;i++){
          cout<<a[m[i]]<<" ";
      }
      return 0;
      

      }

    • + 0 comments

      Can you tell me how you prepared logic for this solution. As i can see it is difficult for me to make this logic in one go. Can you give me some tips to build some logic for these type of problems.

    • + 0 comments

      hey hi, pyuish like you my intend was to get that required index as some function of givenIndex ,k and n which didn't generalize so like (i = f(m,k,n) ) then I our ans would be just, a[i] so my question is how did you figure that out? is there some mathematical concept behind it which I'm not aware of.

    • + 0 comments

      you're awesome, but, how did you get this idea ?

    • + 0 comments

      please explain your code...

    • + 0 comments

      can you explain how you came up with this loglic ie. how you think about it

    • + 0 comments

      @piyush121, I got your answer but will you please tell me how you think problem like that ? I didn't know that we can make logics like that.

    • + 0 comments

      I did something similar with Python, I imagined it as conveyer belt going back and forth, outcome for mod moves it ahead and q pulls it back...

      #!/bin/python3
      
      n, k, q = list(map(int, input().rstrip().split()))
      
      arr = list(map(int, input().rstrip().split()))
      
      while q:
      
          offset = int(input()) - (k%n)
      		
          if offset < 0:
              offset += n
      				
          print(arr[offset])
          q -= 1
      
    • + 0 comments

      can u please explain this logic

    • + 0 comments

      python solution.
      from collections import deque
      def circularArrayRotation(a, k, queries):
      b=deque(a)
      b.rotate(k)
      for i in queries:
      print(b[i])

    • + 0 comments
      def circularArrayRotation(a, k, queries):
          k = k%len(a)
          a = a[-k:] + a[:-k]
          res= []
          for i in queries:
              res.append(a[i])
          return res
      
    • + 0 comments
      how these approach comes in your mind rather than brute force ..................how man how???????????? please tell me bro
      
    • + 0 comments

      I used the same logic in c as of the first program but it isn't passing the sample case

    • + 0 comments

      SEE WHAT IS Actually happening

      import java.util.*; public class Main { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(),k=sc.nextInt(),q=sc.nextInt(); int arr[]=new int[n]; for(int i=0;i0) { int qq=sc.nextInt(); System.out.println(arr1[qq]); } } }

    • + 0 comments

      See What is Actually happening

      	import java.util.*;
      public class Main
      {
          public static void main(String args[])
          {
              Scanner sc=new Scanner(System.in);
              int n=sc.nextInt(),k=sc.nextInt(),q=sc.nextInt();
              int arr[]=new int[n];
              for(int i=0;i<n;i++)
              {
                  arr[i]=sc.nextInt();
              }
              int arr1[]=new int[n];
              k=k%n;
              for(int i=0;i<n;i++)
              {
                  arr1[i]=arr[(i+(n-k))%n];
              }
              while(q-->0)
              {
                  int qq=sc.nextInt();
                  System.out.println(arr1[qq]);
              }
          }
      }
      </code>
      
    • + 0 comments

      Can you explain me the logic behind it!! i solved this it goes correctly but how do you think this logic?? please explain me:

    • + 0 comments

      Faster O(1) time and can be done in O(1) space also ... but i ve used more variables for better understanding....

      include using namespace std;

      int main(){

      int noOfCases, len, rots, newPosi, temp, i, ans, newLen;
      
      cin >> len >> rots >> noOfCases;
      
      int arr[len];
      
      for(i=0; i<len; i++){
          cin >> arr[i];
      }
      
      while(noOfCases != 0){
          cin >> newPosi;
          temp = rots/len;
          newLen = len*(temp+1);
      
          ans = (newPosi + newLen - rots)%len;
      
          cout << arr[ans] << endl;
      
          noOfCases --;
      }
      

      }

    • + 0 comments

      I do have huge respect for this logic :#mod based....amazing

    • + 2 comments

      An easy Approch with vector insert and pop_back. 1 2 3 4 5 after 1st rotation 5 1 2 3 4 after second rotation 4 5 1 2 3 after 3rd rotation 3 4 5 1 2 and so on .........

          while(k--){
              int temp;
              temp=a[a.size()-1];
              a.insert(a.begin(),temp);
              a.pop_back();
          }
      vector<int>arr;
      for(int i=0; i<queries.size();i++)
             arr.push_back(a[queries[i]]);
      
      return arr;
      }
      
      • + 0 comments

        nice sir

    • + 0 comments

      hi can you explain how it is taking O(1) space when you are using :

      int[] a = new int[n];
      
          That will aquire a space of O(1)
      
    • + 0 comments

      may i know the purpose of getting remainder of two inputs