Skip to content

Instantly share code, notes, and snippets.

@feliperazeek
Created October 14, 2016 05:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feliperazeek/53b72d455c2cdf32c594b11eddeb7d0b to your computer and use it in GitHub Desktop.
Save feliperazeek/53b72d455c2cdf32c594b11eddeb7d0b to your computer and use it in GitHub Desktop.
HackerRank - Cracking the Code Interview - Arrays: Left Rotation (https://www.hackerrank.com/challenges/ctci-array-left-rotation)
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) {
if (k < 0) throw new RuntimeException("K needs to be greater than zero");
if (k == 0) return a;
int initial = k;
int[] results = new int[a.length];
for (int i = 0; i < a.length; i++) {
int position = i + k;
if (position > (a.length - 1)) position = position - a.length;
results[i] = a[position];
}
return results;
}
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment