1.

How do you rotate an array?

Answer»

You will be given an input number N and N numbers following it as the input. You are ALSO given an integer K which represents how many times you have to rotate the array. Rotate the array K values to the right if K is positive and K values to the left if K is negative. If K=0, do not rotate the array.

The figure shows how the rotating array will look if k=2.

Approach:

  1. If the value of K is positive then do K=K%N where N is the LENGTH of the input array for eg: if k =10 and N=3 then k will become 1 which means rotating the array 10 times is EQUIVALENT to rotating the array 1 time.
    Similarly, If the value of K is negative, K=K%N + N.
  2. Reverse the first part of the array i.e. from 0 to N-K-1 and the second part from N-K to N-1 separately.
  3. Reverse the entire array i.e. from 0 to N-1. K determines how the array will be rotated.

Code:

import java.io.*;import java.util.*;public class Main { public static void display(int[] arr) { StringBuilder sb = new StringBuilder();for (int val : arr) { sb.append(val + " "); } System.out.println(sb); } public static void reverse(int[] arr, int li, int ri) { while (li < ri) { int t = arr[li]; arr[li] = arr[ri]; arr[ri] = t; li++; ri--; } }  public static void rotate(int[] arr, int k) { k = k % arr.length; if (k < 0) { k += arr.length; } reverse(arr, 0, arr.length - k - 1); reverse(arr, arr.length - k, arr.length - 1); reverse(arr, 0, arr.length - 1); } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(br.readLine()); } int k = Integer.parseInt(br.readLine()); rotate(arr, k); display(arr); }


Discussion

No Comment Found