Day 14 of 30-Day LeetCode Challenge

Aanchal Patial
1 min readApr 14, 2020


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

  • direction can be 0 (for left shift) or 1 (for right shift).
  • amount is the amount by which string s is to be shifted.
  • A left shift by 1 means remove the first character of s and append it to the end.
  • Similarly, a right shift by 1 means remove the last character of s and add it to the beginning.

Return the final string after all operations.

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

static auto x = [](){
return nullptr;

class Solution {

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
//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);



Aanchal Patial

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