Array Question 8

Home / Java Practice Question / Array Question 8

Array Question 8


Question 8. Write a Program to rotate the array in right by k steps, where k is non-negative.

Program- 


class Solution {

    public void reverse(int[] nums, int start, int end){

       int temp=0;

        while(start<end){

            temp=nums[end];

            nums[end]=nums[start];

            nums[start]=temp;

            start++;

            end--;

        }

    }    

    public void rotate(int[] nums, int k) {

        int n=nums.length;

        k=k%n;

        reverse(nums, 0, n-k-1);

        reverse(nums, n-k, n-1);

        reverse(nums, 0, n-1);  

    }

}