cppintermediate10 minutes

Build a Function to Rotate a Vector by k Positions

Write a C++ function that takes a vector of integers and an integer k, and returns the vector rotated to the right by k positions. This exercise tests your understanding of vector manipulation, modular arithmetic, and function implementation.

Challenge prompt

Create a function named rotateVector that accepts a vector<int> and an integer k. The function should return a new vector where the elements are rotated to the right by k positions. For example, rotating [1, 2, 3, 4, 5] by 2 positions results in [4, 5, 1, 2, 3]. Make sure the function handles cases where k is greater than the length of the vector.

Guidance

  • Use modular arithmetic to handle rotation values greater than the vector size.
  • Consider creating a new vector and placing elements at their rotated positions.
  • Avoid modifying the input vector directly if you want to preserve immutability.

Hints

  • To find the new position for an element originally at index i, use (i + k) % size.
  • Think about how to split and recombine the vector into two parts to achieve rotation efficiently.

Starter code

#include <vector>
using namespace std;

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

Expected output

[4, 5, 1, 2, 3]

Core concepts

vectorsmodular arithmeticfunction implementation

Challenge a Friend

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