We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Practice
  • Certification
  • Compete
  • Career Fair
  • Hiring developers?
  1. Practice
  2. Algorithms
  3. Implementation
  4. Circular Array Rotation
  5. Discussions

Circular Array Rotation

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • piyush121 5 years ago+ 0 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]);
        }               
    }
    
    233|
    Permalink
  • Contest Calendar
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature