A little help.?

i am new at this thing. can anyone please explain the soluntion provided??

Do you still want the approach to solution ?

I won’t explain the solution directly but i will help you explain the approach.

Let’s say you have a list of 5 items A = {1, 2, 3, 4, 5}
You want to reverse for valule B = 3;

A simple solution is to

  • reverse from 0 to B = {3, 2, 1, 4, 5}
  • reverse from B to len(A). {3, 2, 1, 5, 4}
  • reverse from 0 to len of A. {4, 5, 3, 2, 1}

This is the answer !

The solution in Java:

public static ArrayList rotateArray(List A, int B) {
ArrayList ret = new ArrayList();
for (int i = 0; i < A.size(); i++) {
//Taking the modules as If b is equal to a.size, the list will remain same
B %= A.size();

        //Calculating the index to fill in ret
        int index = i + B;
        //If index is greater than A.size then reduce the index by A.size to rotate the elements
        if (index >= A.size()) {
            index -= A.size();
        }
        ret.add(A.get(index));
    }
    return ret;
}

Please let me know if this can be optimized further.

Click here to start solving coding interview questions