Lesson 2
Advanced Vector Manipulation Techniques in C++
Lesson Overview

Welcome to another pivotal lesson in your C++ interview preparation. In this lesson, we will concentrate on Advanced Vector Manipulation Techniques, focusing on the representation and manipulation of vectors directly, without relying on built-in functions. This topic is indispensable when preparing for technical interviews, as many problems often involve performing various operations on vectors.

In-Place Modification

Before diving into this lesson's example, let's quickly review In-Place Modification. In-place modification refers to changing the data structure (e.g., a vector) directly, without using extra space for another copy of the data structure. By modifying the original vector directly, we save on memory and may improve performance. This is often achieved by altering the elements within the vector itself rather than creating a new vector to hold the transformed elements.

Vector Rotation In-Place

Let's look at a common coding interview question. You are given a vector nums, and a number k. The task requires "rotating" the vector by k positions. Rotating a vector by k positions means that each element is shifted to the right by k positions, and elements that move past the end wrap around to the beginning. For example, rotating the vector [1, 2, 3, 4, 5, 6, 7] to the right by 3 positions results in [5, 6, 7, 1, 2, 3, 4]. Elements that move past the end of the vector wrap around to the beginning.

One approach is creating an empty vector and copying the elements of the original vector, calculating shifts to create a new rotated vector. However, in this challenge, we must rotate the vector in-place. We cannot create a new vector to aid in our algorithm.

Here, we'll use a four-step approach involving vector reversal to achieve this in-place and efficiently.

  1. Adjust k to be within bounds: Calculate k = k % n to ensure k lies within the range [0, n-1]. Here, n is the size of the vector. This step handles cases where k is larger than n, effectively reducing unnecessary full rotations.

  2. Reverse the entire vector: Reversing the entire vector will place the last k elements (which need to be moved to the front) in the first k positions, but in reverse order.

  3. Reverse the first k elements: Reversing just these first k elements restores their original order.

  4. Reverse the remaining elements: Finally, reversing the elements from position k to the end restores the order of the remaining elements.

Let's look at an example:

Given an initial vector nums=[1, 2, 3, 4, 5, 6, 7] and k = 3:

  • Reverse the entire vector: nums = [7, 6, 5, 4, 3, 2, 1]
  • Reverse the first 3 elements: nums = [5, 6, 7, 4, 3, 2, 1]
  • Reverse the rest of the vector: nums = [5, 6, 7, 1, 2, 3, 4]

The nums vector has been successfully rotated to the right by 3.

Our solution will use the std::reverse function from the C++ Standard Library to achieve the reversals efficiently.

C++
1#include <iostream> 2#include <vector> 3#include <algorithm> // Include for std::reverse 4 5void rotateVector(std::vector<int>& nums, int k) { 6 int n = nums.size(); 7 k = k % n; // Ensure k is within the bounds of the vector length 8 9 // Reverse the entire vector 10 std::reverse(nums.begin(), nums.end()); 11 // Reverse the first k elements 12 std::reverse(nums.begin(), nums.begin() + k); 13 // Reverse the rest of the vector 14 std::reverse(nums.begin() + k, nums.end()); 15} 16 17// Example 18int main() { 19 std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7}; 20 int k = 3; 21 22 rotateVector(nums, k); 23 24 for(int num : nums) { 25 std::cout << num << " "; 26 } 27 // Output: 5 6 7 1 2 3 4 28 29 return 0; 30}
Rotate Vector Breakdown

Now let's break down the rotateVector function.

Function Definition

This line defines the rotateVector function which takes a reference to an std::vector<int> and an integer k. The function doesn't return any value (void). It simply modifies the nums vector.

C++
1void rotateVector(std::vector<int>& nums, int k)

Calculate Vector Size

We calculate the size of the vector and store it in the variable n. This is used to handle rotations efficiently.

C++
1int n = nums.size();

Adjust k to be Within Bounds

This line calculates k % n to ensure k lies within the range [0, n-1]. This step handles cases where k is larger than n, effectively reducing unnecessary full rotations.

C++
1k = k % n; // Ensure k is within the bounds of the vector length

Reverse the Entire Vector

We next use the std::reverse function to reverse the entire vector. This operation moves the last k elements to the front but in reverse order.

C++
1std::reverse(nums.begin(), nums.end());

Reverse the First k Elements

Next, we use the std::reverse function to reverse the first k elements. This restores their original order.

C++
1std::reverse(nums.begin(), nums.begin() + k);

Reverse the Remaining Elements

Lastly, we use the std::reverse function to reverse the elements from position k to the end of the vector. This restores the order of the remaining elements after k.

C++
1std::reverse(nums.begin() + k, nums.end());

The rotateVector function effectively rotates the given vector to the right by k positions through a combination of three reversal operations using the std::reverse function, resulting in an efficient, in-place rotation.

Lesson Summary

In this lesson, we explored Advanced Vector Manipulation Techniques such as rotating a vector by k positions. Remember, our goal isn't simply to memorize algorithms but to develop an understanding of how to systematically break down and address problems — a skill that is at the heart of programming. As always, practice is your best friend, so let's get coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.