@xsh6528 said in 3 lines of C++ in one pass using swap:

I cannot understand the condition k %= n

A example that is related to this condition.

k
n
nums
3
8
1,2,3,4,5,6,7,8
3
5
6,7,8,4,5,1,2,3
1
2
6,7,8,1,2,3,5,4
0
1
6,7,8,1,2,3,4,5
````````
`````````
I expect [6,7,8,4,5,1,2,3] becomes [6,7,8,1,2,3,4,5],

but due to swap, it has to become [6,7,8,1,2,3,5,4] first,

but k = 1, handles this case subtly.

Any one can explain this ?

@xsh6528 You almost got it! Ask yourself, can k be bigger than n? Of course not, you cannot rotate an array by more than the array length. In your table, you see when n drops to 2 in the third row, we have to adjust k by taking its modulus of n (2 in this case), so we get k = 3%2 = 1.