There is a common problem to rotate an array by k steps. It can be easily done with O(n) time complexity and O(n) space complexity. There is a trick to solve this problem with O(n) time complexity and O(1) space complexity. It involves the following 3 steps.
-
Reverse the whole array of size n.
-
Reverse the first k element.
-
Reverse the next (n-k) element.
It's really hard to figure out this solution. But you can keep this trick in your mind, it would help you in other problems.
Link of complete code: https://github.com/prashantkumars289/Rotate_an_array_by_k_steps/blob/main/rotate_array.cpp