EduLearn - Online Education Platform

Welcome to EduLearn!

Start learning today with our wide range of courses taught by industry experts. Gain new skills, advance your career, or explore new interests.

Browse Courses

Given an integer array nums[], rotate the array to the right by k steps, where k is non-negative.

 

Example 1:

Input: nums = [1,2,3,4,5,6,7], k = 3

Output: [5,6,7,1,2,3,4]

Explanation:

rotate 1 steps to the right: [7,1,2,3,4,5,6]

rotate 2 steps to the right: [6,7,1,2,3,4,5]

rotate 3 steps to the right: [5,6,7,1,2,3,4]

 

————————————————–

class RotateArray

{

static void rotateArray(int arr[],int n,int k)

{

int temp[]=new int[k];

 

for(int i=0;i<k;i++)//2<2

{

temp[i]=arr[n-k+i];// temp[1]=arr[4]

}

for(int i=n-1;i>=k;i–)//i=2;2>=2

{

arr[i]=arr[i-k];//arr[2]=arr[0]

}

for(int i=0;i<k;i++)//i=1;1<2

{

arr[i]=temp[i];//arr[1]=temp[1]

}

 

}

public static void main(String args[])

{

int arr[]={1,2,3,4,5};

int n=arr.length;//5

int k=2;//rotate by 2 position

 

rotateArray(arr,n,k);

 

System.out.println(“Rotated Array=”);

for(int i=0;i<n;i++)

{

System.out.println(arr[i]);

}

}}

Java practice programs for leetcode

Leave a Reply

Your email address will not be published. Required fields are marked *

EduLearn - Online Education Platform

Welcome to EduLearn!

Start learning today with our wide range of courses taught by industry experts. Gain new skills, advance your career, or explore new interests.

Browse Courses

Popular Courses

[Course Image]

Introduction to Programming

Learn the fundamentals of programming with Python in this beginner-friendly course.

12 Hours Beginner
[Course Image]

Data Science Essentials

Master the basics of data analysis, visualization, and machine learning.

20 Hours Intermediate
[Course Image]

Web Development Bootcamp

Build modern websites with HTML, CSS, JavaScript and popular frameworks.

30 Hours Beginner
[Course Image]

Digital Marketing Fundamentals

Learn SEO, social media marketing, email campaigns and analytics.

15 Hours Beginner
Educational Website Footer