Skip to content

Instantly share code, notes, and snippets.

@Ram-1234
Last active January 3, 2021 05:50
Show Gist options
  • Save Ram-1234/b4e89ecfdc0cfa35d2e4de32458ff670 to your computer and use it in GitHub Desktop.
Save Ram-1234/b4e89ecfdc0cfa35d2e4de32458ff670 to your computer and use it in GitHub Desktop.
InterviewBit ARRAY_BUG
The following code is supposed to rotate the array A by B positions.
Explanation
Input:-1
A : [1 2 3 4 5 6]
B : 1
Input:-2
A:[ 14, 5, 14, 34, 42, 63, 17, 25, 39, 61, 97, 55, 33, 96, 62, 32, 98, 77, 35 ]
B:56
Output:-1
[2 3 4 5 6 1]
Output:-2
[35 14 5 14 34 42 63 17 25 39 61 97 55 33 96 62 32 98 77]
#######################JAVA CODE##########################
public class Solution {
public ArrayList<Integer> rotateArray(ArrayList<Integer> A, int B) {
ArrayList<Integer> ret = new ArrayList<Integer>();
int l=(int)A.size();
if(B<=l){
for (int i = 0; i < A.size(); i++) {
ret.add(A.get((i + B)%l));
}
}
else{
B=(int)B%l;
for (int i = 0; i < A.size(); i++) {
ret.add(i,A.get((i + B)%l));
}
}
return ret;
}
}
///////////////////slite change code//////////////////////////
#############################################################
public class Solution {
public ArrayList<Integer> rotateArray(ArrayList<Integer> A, int B) {
ArrayList<Integer> ret = new ArrayList<Integer>();
for (int i = 0; i < A.size(); i++) {
ret.add(A.get((i + B%A.size())%A.size()));
}
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment