You are viewing a single comment's thread. Return to all comments →
mine is also a brute force approach but it worked check it out if it helps you
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static int[] arrayLeftRotation(int[] a, int n, int k) { int temp,i,j; for(i=0;i<k;i++){ temp=a[0]; for(j=1;j<n;j++){ a[j-1]=a[j]; } a[n-1]=temp; } return a; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int a[] = new int[n]; for(int a_i=0; a_i < n; a_i++){ a[a_i] = in.nextInt(); } int[] output = new int[n]; output = arrayLeftRotation(a, n, k); for(int i = 0; i < n; i++) System.out.print(output[i] + " "); System.out.println(); } }
int main(){ int n; int k; int temp1, temp2; scanf("%d %d",&n,&k); int *a = malloc(sizeof(int) * n); for(int a_i = 0; a_i < n; a_i++){ scanf("%d",&a[a_i]); } k = k %n; for(int a_i = 0; a_i < k; a_i++){ temp1 = a[0]; for(int i = 1; i < n; i++){ a[i-1] = a[i]; } a[n-1] = temp1; } for(int a_i = 0; a_i < n; a_i++){ printf("%d ", a[a_i]); } return 0; }
my code is the same as yours but i still time in test case 8, why is that?
You're not wrong but this solution is inefficient. You're solving it in O(((n-1) * k) + 2n). The solution below is in O(2n).
private static void solution(int size, int shift, int[] arr) { int count = 0; for (int i = shift; i < size; i++) { System.out.print(arr[i]); System.out.print(" "); count++; } count = 0; for (int i = size - shift; i < size; i++) { System.out.print(arr[count]); if (i != size - 1) System.out.print(" "); count++; } }
Seems like cookies are disabled on this browser, please enable them to open this website
I agree to HackerRank's Terms of Service and Privacy Policy.
Arrays: Left Rotation
You are viewing a single comment's thread. Return to all comments →
mine is also a brute force approach but it worked check it out if it helps you
my code is the same as yours but i still time in test case 8, why is that?
You're not wrong but this solution is inefficient. You're solving it in O(((n-1) * k) + 2n). The solution below is in O(2n).