Why use .size() in solution?


#1

What is the .size() for used over here ( taken from editorial solution)

ret.push_back(A[(i + B)%A.size()]);

#2

size() is to calculate length of List here ArrayList since, we can’t use length() for List type.


#3

Lets consider A to have 5 elements and B to be 2.

| 1 | 2 | 3 | 4 | 5 |

Lets also declare new array “ret” to copy the result.

first iteration-
i=0 so A[(0+2)%5]=A[2]=3
push_back(3) to ret
ret contains 3

second iteration-
i=1 so A[(1+2)%5]=A[3]=4
push_back(4) to ret
ret contains 3 4

third iteration-
i=2 so A[(2+2)%5]=A[4]=5
push_back(5) to ret
ret contains 3 4 5

fourth iteration-
i=3 so A[(3+2)%5]=A[0]=1
push_back(1) to ret
ret contains 3 4 5 1

fifth iteration-
i=4 so A[(4+2)%5]=A[1]=2
push_back(2) to ret
ret contains 3 4 5 1 2

if i = 5 loop breaks and returns ret