top of page

Daily Coding Problem #16

Writer's picture: Mischievous_FaceMischievous_Face

// Write a function that rotates a list by k elements. For example, [1, 2, 3, 4, 5, 6] rotated by two becomes // [3, 4, 5, 6, 1, 2].

// Try solving this without creating a copy of the list. How many swap or move operations do you need?


#include <iostream>

#include <string>

#include <vector>


using namespace std;


vector<int> rotateVector(vector<int> vec, int k)

{

if (vec.size() < 2)

return vec;


int next;

int prev;


for (unsigned i = 0; i < k; ++i)

{

prev = vec[vec.size() - 1];


for (unsigned j = 0; j < vec.size(); ++j)

{

int curr = vec[j];

vec[j] = prev;

prev = curr;

}

}


return vec;

}



int main()

{

int k = 2;

vector<int> vec;

vec.push_back(1);

vec.push_back(2);

vec.push_back(3);

vec.push_back(4);

vec.push_back(5);

vec.push_back(6);


auto result = rotateVector(vec, k);


for (unsigned i = 0; i < result.size(); ++i)

{

cout << result[i] << ", ";

}


return 0;

}

118 views0 comments

Recent Posts

See All

Comments


© 2020 Josh Painter

bottom of page