Java Program to Rotate the elements of an array to the left By N times | Interview Question Answers
Вставка
- Опубліковано 23 гру 2024
- In this video, we demonstrated how to Rotate the elements of an array to the left By N times.
Input Array - {1 2 3 4 5}
N - 3
Output Array - {4 5 1 2 3}
#java
#javacoding
#javainterviewquestions
#javaprogramming
#coding
Can we use queue where we pop the first element and push It to the end
class position{
public static void main(String[] args){
int[] a={1,2,3,4,5};
int temp=a[2];
a[2]=a[4];
a[4]=temp;
System.out.println(java.util.Arrays.toString(a));
}
}
package arrays;
public class RotateArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {1, 2, 3, 4, 5, 6, 7,8};
int val = 12;
if (val == 0)
return;
int n = arr.length;
// in case the rotating factor is
// greater than array length
val = val % n;
System.out.println(val);
removeElement(arr, 0, val - 1);
removeElement(arr, val, n - 1);
removeElement(arr, 0, n - 1);
printArray(arr);
}
private static int[] removeElement(int[] arr, int start, int end) {
// TODO Auto-generated method stub
int temp;
while (start < end) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
return arr;
}
private static void printArray(int[] arr) {
// TODO Auto-generated method stub
for(int i=0;i
The time complexity is now O(n), great man
Nice bro
int arr[]={1,2,3,4,5};
int n=3;
for(int i=0;i
in second for loop at the loop end you use "i++" instead of "j++" . correct it and rerun you got the output
Output i am getting is 34513
public class Main{
public static void main(String[] args) {
int[] raju= new int[] {1,2,3,4,5};
int n=3;
for(int i=0;i
public class Practice {
public static void main(String[] args) {
int[] raju= new int[] {1,2,3,4,5};
int n=3;
for(int i=0;i