Build a Function to Rotate an Array by k Steps
Create a C++ function that rotates the elements of an integer array to the right by k steps. This function should handle cases where k is greater than the array length and work efficiently without using extra space for another array.
Challenge prompt
Write a function named rotateArray that takes a vector of integers and an integer k, which represents the number of steps to rotate the array to the right. Your function should modify the original vector in place and handle cases where k is greater than the length of the array. The rotation should be done efficiently with minimal extra memory use.
Guidance
- • Consider using the modulo operator to handle cases where k is larger than the vector size.
- • Try reversing parts of the array to achieve the rotation instead of shifting elements one by one.
Hints
- • Rotating an array right by k is equivalent to moving the last k elements to the front.
- • You can reverse the entire array, then reverse the first k elements, and finally reverse the remaining elements to get the rotated array.
Starter code
void rotateArray(std::vector<int>& nums, int k) {
// Your code here
}Expected output
For example, given nums = {1, 2, 3, 4, 5, 6, 7} and k = 3, after rotateArray(nums, 3), nums should be {5, 6, 7, 1, 2, 3, 4}.
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.