Rotate Array | Array Problem

4 years ago Lalit Bhagtani 0

Problem Statement

You have given array and an integer K. Write a program to rotate the array to the right by K steps.

Example 

Rotate Array

Input :- [1, 2, 3, 4, 5, 6, 7] and K = 4
Output :- [4, 5, 6, 7, 1, 2, 3]
Input :- [1, 2, 3, 4, 5, 6, 7] and K = 20
Output :- [2, 3, 4, 5, 6, 7, 1]

Solution

The reverse approach can be used to solve this problem, in this approach when we rotate the array K times, then K elements from the back of the array come to the front and the rest of the elements from the front shift backward.

Firstly reverse all the elements of the array, then reverse first K elements followed by reversing the rest n – K elements.

Program

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		int[] result = main.rotate(new int[] {1, 2, 3, 4, 5, 6, 7}, 20);
		for(int i : result) {
			System.out.print(i + ", ");	
		}			
	}
	
	/* Solution */    
	public int[] rotate(int[] nums, int k) {

        k = k % nums.length;
        if(k == 0) return nums;

        reverse(0, nums.length, nums);
        reverse(0, k, nums);
        reverse(k, nums.length, nums); 
        return nums;
    }

	public void reverse(int start, int end, int[] nums) {        
        
    	int i = start;
        int j = end-1;
        
        while(i < j){
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
            i++;
            j--;
        }
    }
}

Result

2, 3, 4, 5, 6, 7, 1, 

Similar Post

  1. Maximum Subarray
  2. Positions of Large Groups
  3. Find the Duplicate Number in Array

That’s all for Rotate Array in Java, If you liked it, please share your thoughts in a comments section and share it with others too.