Rotate List Left by K in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of numbers. We have to define a method that can rotate a list of numbers to the left by k elements.

So, if the input is like [5,4,7,8,5,6,8,7,9,2], k = 2, then the output will be [8,5,6,8,7,9,2,5,4,7]

To solve this, we will follow these steps −

  • Define an array ret

  • n := size of nums

  • k := k mod n

  • for initialize i := k, when i < n, update (increase i by 1), do −

    • insert nums[i] at the end of ret

  • for initialize i := 0, when i < k, update (increase i by 1), do −

    • insert nums[i] at the end of ret

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v) {
   cout << "[";
   for (int i = 0; i < v.size(); i++) {
      cout << v[i] << ", ";
   }
   cout << "]" << endl;
}
class Solution {
   public:
   vector<int> solve(vector<int>& nums, int k) {
      vector <int> ret;
      int n = nums.size();
      k %= n;
      for(int i = k; i < n; i++){
         ret.push_back(nums[i]);
      }
      for(int i = 0; i < k; i++){
         ret.push_back(nums[i]);
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<int> v = {5,4,7,8,5,6,8,7,9,2};
   print_vector(ob.solve(v, 3));
}

Input

{5,4,7,8,5,6,8,7,9,2}, 2

Output

[8, 5, 6, 8, 7, 9, 2, 5, 4, 7, ]
raja
Published on 02-Sep-2020 12:26:13
Advertisements