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.
Circular Array Rotation
Circular Array Rotation
+ 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]); } }
+ 0 comments Here is another Java solution
public static void main(String[] args) { Scanner in = new Scanner(System.in); int n, k ,q; n = in.nextInt(); k = in.nextInt(); q = in.nextInt(); int[] arr = new int[n]; for(int i=0; i<n; i++) { arr[(i+k)%n] = in.nextInt(); } for(int i=0; i<q; i++) { System.out.println(arr[in.nextInt()]); } }
+ 0 comments Long live Python and its negative indexes ;)
+ 0 comments We don't need to actually rotate the array. We can just use basic math to pull the entry from the original array:
int shift = n - (k % n); int index = (shift + m ) % n;
+ 0 comments static int[] circularArrayRotation(int[] a, int k, int[] queries) { int arr[] = new int[a.length]; for(int i=0 ; i<a.length ; i++) arr[(i+k)%a.length] = a[i]; for(int i=0 ; i<queries.length ; i++) queries[i] = arr[queries[i]]; return queries; }
Load more conversations
Sort 2305 Discussions, By:
Please Login in order to post a comment