# Day 14 of 30-Day LeetCode Challenge

You are given a string `s` containing lowercase English letters, and a matrix `shift`, where `shift[i] = [direction, amount]`:

Return the final string after all operations.

C++ Solution : O(n) time & O(1) space

static auto x = [](){
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return nullptr;
}();

class Solution {
public:

string shiftByK(string s, int k){
reverse(s.begin(), s.begin()+k);
reverse(s.begin()+k, s.end());
reverse(s.begin(), s.end());
return s;
}

string stringShift(string s, vector<vector<int>>& shift) { //O(n) time & O(1) space
int shiftValue = 0;
//left shift : negative
//right shift : positive
for(int i=0;i<shift.size();++i){
if(shift[i][0]==0) shiftValue += (-1*shift[i][1]);
else if(shift[i][0]==1) shiftValue += shift[i][1];
}
int k = 0; //rotate string anti-clockwise k time
if(shiftValue<0){
//left shift by abs(shift)
if(abs(shiftValue)>s.size()) shiftValue = abs(shiftValue)%s.size();
k = abs(shiftValue);
}else if(shiftValue>0){
//right shift by abs(shift)
if(shiftValue>s.size()) shiftValue = shiftValue%s.size();
k = s.size()-shiftValue;
}
return shiftByK(s, k);
}
};

--

--

## More from Aanchal Patial

We never really grow up, we only learn how to act in public

## Get the Medium app

We never really grow up, we only learn how to act in public