A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer,d, rotate the array that many steps left and return the result.
Example:
Input: n=5,d=4, arr[]={1,2,3,4,5}
Output: 5 1 2 3 4
Approach
Java
import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;public class LeftRotation {public static void main(String[] args) {int d = 4;int[] arr = { 1, 2, 3, 4, 5 };arr = rotateLeft(d, arr);System.out.println(Arrays.toString(arr));}private static int[] rotateLeft(int d, int[] arr) {{int n = arr.length;d = d % n;int temp[] = new int[d];for (int i = 0; i < d; i++) {temp[i] = arr[i];}int l = 0;for (int i = d; i < n; i++) {arr[l++] = arr[i];}for (int i = 0; i < d; i++) {arr[l++] = temp[i];}return arr;}}// input array listpublic static List<Integer> rotateLeft(int d, List<Integer> list) {int[] arr = list.stream().mapToInt(Integer::intValue).toArray();int n = arr.length;d = d % n;int temp[] = new int[d];for (int i = 0; i < d; i++) {temp[i] = arr[i];}int l = 0;for (int i = d; i < n; i++) {arr[l++] = arr[i];}for (int i = 0; i < d; i++) {arr[l++] = temp[i];}list = Arrays.stream(arr).boxed().collect(Collectors.toList());return list;}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> rotateLeft(int d, vector<int> arr){int n = arr.size();d = d % n;int temp[d];for (int i = 0; i < d; i++){temp[i] = arr[i];}int l = 0;for (int i = d; i < n; i++){arr[l++] = arr[i];}for (int i = 0; i < d; i++){arr[l++] = temp[i];}return arr;}int main(){int n = 5, d = 4;vector<int> arr = {1, 2, 3, 4, 5};arr = rotateLeft(d, arr);for (int i = 0; i < n; i++){cout << arr[i] << " ";}return 0;}
No comments:
Post a Comment