cppintermediate10 minutes

Build a Function to Rotate Elements in an Array

Write a C++ function that rotates the elements of an array to the right by a given number of steps. The rotation should handle cases where the number of steps is larger than the array size.

Challenge prompt

Create a function named rotateArray that takes a vector of integers and an integer k representing the number of rotation steps. The function should rotate the array to the right by k steps in-place, meaning elements shifted off the end reappear at the front. Return the rotated vector after performing the operation. For example, given nums = {1, 2, 3, 4, 5, 6, 7} and k = 3, the function should return {5, 6, 7, 1, 2, 3, 4}.

Guidance

  • Consider how to handle the case when k is larger than the size of the vector.
  • Think about using vector slicing or three-step reversal to achieve the rotation efficiently.

Hints

  • Using modulo (k % nums.size()) can simplify handling rotations greater than the vector length.
  • One approach is to reverse the entire vector, then reverse the first k elements and finally reverse the remaining elements.

Starter code

#include <vector>
using namespace std;

vector<int> rotateArray(vector<int>& nums, int k) {
    // Your code here
}

Expected output

rotateArray({1, 2, 3, 4, 5, 6, 7}, 3) -> {5, 6, 7, 1, 2, 3, 4} rotateArray({-1, -100, 3, 99}, 2) -> {3, 99, -1, -100}

Core concepts

arraysin-place modificationmodular arithmeticvector operations

Challenge a Friend

Send this duel to someone else and see if they can solve it.