- Practice
- Data Structures
- Arrays
- Left Rotation
- Discussions

# Left Rotation

# Left Rotation

akueisara39 + 50 comments This is my solution in Java

`public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int d = scan.nextInt(); int[] array = new int[n]; for(int i=0; i<n;i++) { array[(i+n-d)%n] = scan.nextInt(); } for(int i=0; i<n;i++) { System.out.print(array[i] + " "); } } }`

- RK
ramkr7 + 1 comment can i get an explanation,pls?

akueisara39 + 6 comments Each time I read an element of the array from the input, I directly assign it to the array at the speific index after shifting. d left rotations equal (n-d) right rotations. The array has a size of n, so when the index (i+n-d) is equal to n, the index actually goes back to the starting index. I use mod to get the correct index where I want to assign the element when the index is larger than n. I'm not an english native speaker. Hope you will understand what I explain. :)

motox2 + 1 comment I see a problem here. You've assumed that we can sort the array at the time of initialization itself. Though it's good, but IMHO, the real test is to sort an already existing array with space constraints.

- Q
qianyaonan + 12 comments Good thinking! I guess it could be handled with another array logically. My two cents.

`...... int[] getArray = new int[n]; for (int i = 0; i < n; i++) { getArray[i] = scan.next(); } for (int i = 0; i < n; i++) { array[(i + n - d) % n] = getArray [i]; } for(int i = 0; i < n; i++) { System.out.print(array[i] + " "); }`

suulisindiyaka + 2 comments I like you code some much.PLEASE can you add some explainatioin.I will be very glad

- Q
qianyaonan + 1 comment It just generates an array first from Stdin, then illustrates the way to left-rotate an EXISTING array.

- VA
vamphonephong + 0 comments I'm failing to see where it actually does a left rotate of an existing array.

What I'm seeing is (from assumption of ...) array[0..n] is empty initially. getArray[0..n] stores input from stdin. store rotated result into array[0..n].

The existing array is getArray. That array is still in an unrotated order. The array[0..n] isn't considered the exiting array as it is empty.

Challenge to you: get rid of getArray array and store input into array[] array. Rotate that array and then print the end result of that array.

jeffreyzhuu + 0 comments This code is actually quite efficient. So for the following values, n=5 (number of elements in the array), d=2 (number of rotations)and assuming i goes from 0-4. (i + n - d)%n with the iteration of i from 0-4: (0+5-2)%5=3 (1+5-2)%5=4 . . . (4+5-2)%5=2 So essentially, you are changing the locations of the elements in the array. How the "%" works is that it takes the remainder. So for example, 1%7=1 since 1 cannot be divided by 7 which means 1 is the remainder.

- N
nunziomeli5 + 2 comments That's not the aim of the exercise... You have to fill the array and after shift!!! In this way is easy and you are not resolving the left shift problem.

akueisara39 + 4 comments For me, it's just an alternative way. There's not only one way to think for the same problem whatever the solution is good or bad. I shared my solution because I hadn't seen anyone think the same way and I thought it was good to learn from people's comments on my solution.

- SP
shankar455161 + 0 comments A good solution by you!

ekimalc + 0 comments I like your solution, elegant and efficient. It took my two days for mine and even now has timeout issues when testing. I have good envy now. Well done!

- GY
govind_yadav_141 + 1 comment I really like your solution as you have reduce the time complexity to O(n^2) while is very efficeint compare to my program which has a T(n) = O(n^3)

Sufiyan + 0 comments How the complexity is quadratic? It is O(n), right?

skandy + 1 comment This solution will not work when rotation is greater than array size, meaning d > n. Java returns negative result if you perform % operation on a negative number. And that negative number will throw an

java.lang.ArrayIndexOutOfBoundsException

Eg. n = 4, d = 7

Starting with i=0, a[(i+n-d)%n] will give a[(0 + 4 - 7)%4] => a[(0 + (-3))%4] => a[(-3)%4] => a[-3]

Range of a is from 0 to n. Hence the error

- RT
ravievolution87 + 0 comments for this case you can check for d>n and d = d%n then d will be in range of 0 to n and the above solution will work perfectly :)

allister_quinn + 2 comments It's the far superior solution. Why shift all the elements in the array individually, when you can just shift the index to achieve the same result? It's a total waste of processing to shift the entire array. What if the array was 1,000,000,000 elements long, and you had to shift multiple times? In an interview they would probably expect you to do it this way, with an explanation of your logic.

- JM
Wafflenaut + 0 comments I agree. If they wanted something to shift elements of an array, they should have asked for a function to do so.

eniv230862 + 0 comments In my case, they were expecting the function that returns a vector with all the elements rotated any number of times. So, the best way is to take the number of shiftings and move the index that number of times, and do the shift only one time.

tanp1 + 0 comments Have you tried running this? You actually run into an issue where you just propagate the first value in the array across all other indices in the array using your method.

The second for loop moves the value at index 0, the 1, over to index 1, overwriting the value 2 at index 1, and then this 1 gets written into all the other indices as a result.

- TP
tp2124 + 2 comments Solid answer. I would like to point out to people that this does require double the memory of the intial answer as this requires a second array to store all the properly ordered array. If you're on a memory tight situation, this would not be a favorable solution.

corey_t_ferguson + 2 comments To solve this, I've shifted the elements in the array in O(n) time and O(n) memory (vs O(2n)). Not as easy on the eyes, though :(

function processData(input) { // get `n` and `d` from input const lines = input.split('\n'); const firstLine = lines[0].split(' ').map(Number); const n = firstLine[0]; const d = firstLine[1]; // process each line lines.slice(1, lines.length).forEach(line => { // no need to shift in these cases if (n === 1 || d === n) { console.info(line); } else { // shift digits const a = line.split(' ').map(Number); let lastLastItem = null; let count = 0; let i = 0; while (count < n) { i++; const start = i; let j = start; do { count++; let lastItem = lastLastItem; lastLastItem = a[j]; a[j] = lastItem; j = shiftLeft(n, d, j); } while (j !== start); a[start] = lastLastItem; } console.info(a.reduce((acc, value) => { return acc+' '+value; })); } }); } /** * @param {Number} n total number of elements * @param {Number} d number of shifts to left * @param {Number} i index to begin shifting from * @returns {Number} new index after shifting to left */ function shiftLeft(n, d, i) { return (n-d+i)%n; }

I'm ignoring the processing time on input string manipulation and such. This examples assumes they gave us an existing array to manipulate.

- VJ
vjindal23 + 0 comments Hey! Could you include comments in your code please? I use C and dont kow other language as of now but would like to learn from your solution O(n) is preety nice

- JS
siregar_jaswir + 1 comment i think your solutions is O(n^2) for the worst case.

corey_t_ferguson + 0 comments It looks like it, because of the nested loops. But it'll break out of all loops after

`n`

loops.

corey_t_ferguson + 0 comments Revisited this with an easier-on-the-eyes solution that finishes in O(n) time with O(n) memory.

function main() { // ... loopUntilAllSwapped(a, d); console.log(a.join(' ') + '\n'); } /** * If a.length can be divided by d evenly, swapSeries will end * where it started without swapping all numbers. * This function ensures that all numbers are swapped. * * Variables: * a: array of numbers * d: number of left-rotations to perform * c: count of numbers swapped * i: index to start swapSeries() from */ function loopUntilAllSwapped(a, d) { let c = 0; let i = 0; while (c < a.length) { c += swapSeries(a, i, d); i++; } } /** * Swaps elements in an array in-place. * * Variables: * a: array of numbers * i: index to start with * d: number of left-rotations to perform * c: count of numbers swapped, returned to loopUntilAllSwapped() * iS: index source (index of number to be moved) * iD: index destination (index iS will be moved to) * q: a queue that acts as a temporary buffer for numbers as they * move from source to destination * * Algorithm: * 1. Find index destination (iD) of a[iS] after d rotations to * left * 2. Place destination in temporary buffer (q). * 3. Replace destination with index source (iS) value (a[iS]). * 4. Repeat until we end where we started (iS === i) */ function swapSeries(a, i, d) { let c=0; let iS = i; let q = [a[iS]]; do { let iD = h(a.length, d, iS); q.push(a[iD]); a[iD] = q.shift(); iS = iD; c++; } while (iS !== i); return c; } /** * A constant-time formula to find index destination of i * after d rotations to left. */ function h(n, d, i) { return ((n-d%n)%n+i)%n; }

iam_ghanshyam + 0 comments In my opinion, the 3rd for-loop is unnecessary.. Instead it should be merged with the 2nd one.

alxsm + 0 comments [deleted]- LS
liuch_sdu + 0 comments This should be called circle array,haha

- TJ
tomisin + 0 comments Doesn't this use extra space?

wyrlvillazorda + 1 comment for me is: (d + i) % n

ajinkya_ghonge + 0 comments One drawback i can see here is that you are actually holding the IO operation while your code is getting executed. This will not affect for an input of 100, but think about an input of millions

- 11
karhik110 + 0 comments nice!! different way of thinking! you cahnged the way of thinging..

- PM
pmahanth967 + 0 comments getArray[i] = scan.next(); this is an error.It cannot be converted into string.

getArray[i] = scan.nextInt(); this is correct statement.

justin_gries + 0 comments Very nice. I didn't even think to assign the integers to their "new" positions in the array as they are read in.

anandki + 0 comments Concise code and Wonderful explanation.This should go to Editorial.

- PS
Purushotam_ + 0 comments why can't we do the left rotation. like you said d left rotation is equal to n-d right rotation.what is problem in that...

- V
Infinity_Coder + 0 comments Given an array of n integers and a number, d, perform d left rotations on the array. So this means that the array is already given. Then we have to perform left rotation on that. Your solution may produce the required results, but as others have pointed out, I think that is not what has been asked in the solution. We have been given a complete array, and on that we have to perform the rotation.

akimran3 + 1 comment your code is very small and still work fine, will you explain me how [(i+n-d)%n] is working here. please actually why you are using % here thats making me confuse

- RK
ramkr7 + 1 comment % (modulus) gives you the remainder of division.so 4%5=4,5%5=0 likewise 6%5=1, it helps you to stay inside the limit i.e lesser than the value n (i.e till n-1) eg:if n=5 it goes from 0 to 4.try this simple mod in calc or put it in a loop you will understand.we are getting the input value to the rotated index thats why (-d).if right rotation +d.

alex_k_stamatis + 0 comments It's a great solution but how would someone come up with the idea to use a modulus in this case?

ajaycarnet + 6 comments This is my C# sharp code.

`string[] s1 = Console.ReadLine().Split(' '); int n = int.Parse(s1[0]); int k = int.Parse(s1[1]); string[] s = Console.ReadLine().Split(' '); int[] array = new int[n]; ////pre-rotation of array method: //-----------------------------------Right rotation //for (int i = 0; i < n; i++) //{ // array[(i + k) % n] = int.Parse(s[i]); //} //------------------------------------Left rotation for (int i = 0; i < n; i++) { array[(i + (n-k)) % n] = int.Parse(s[i]); } for (int i = 0; i < n; i++) { Console.WriteLine(array[i]+" "); }`

axaysd + 0 comments THANK YOU SO MUCH FOR THIS SOLUTION!!!!!!!!!!!!!!!!!!!! :')

I've been searching for both right & left shift formulae!!!

- JN
jdnark + 0 comments This code will fail the test. This is the fix:

for (int i = 0; i < n; i++) { Console.Write(array[i]+" "); }

Console.WriteLine();

ermaneesh007 + 1 comment Very slow. & it will not work out 1,000,000,000 records

aayush_break + 0 comments exactly...it's better to follow up with "Reversal algorithm". Follows O(n) time complexity without the usage of any temp storage. Hence saves storage and time both

- PP
Pree92tham + 0 comments Not the desired approach but it gets the job done though

static void Main(String[] args) { string[] token=Console.ReadLine().Split(' '); int n=Convert.ToInt32(token[0]); int k=Convert.ToInt32(token[1]); string[] arr1=Console.ReadLine().Split(' '); int [] arr=Array.ConvertAll(arr1,int.Parse);

`int temp=0; Queue<int> l=new Queue<int>(); for(int i=0;i<n;i++){ l.Enqueue(arr[i]); } for(int j=0;j<k;j++){ temp=l.Dequeue(); l.Enqueue(temp); } foreach(int i in l){ Console.Write("{0} ",i); } }`

- NM
nicholas_mahbou1 + 0 comments Great solution ajaycarnet. I compared yours with my own and yours is much faster.

var sw = Stopwatch.StartNew(); int[] array = new int[n]; for(int i = 0; i < n; i++) array[(i + (n - d)) % n] = int.Parse(s[i]); sw.Stop(); for(int i = 0; i < n; i++) Console.Write(array[i] + " "); Console.WriteLine(); Console.WriteLine(sw.ElapsedTicks); // 5 ticks sw = Stopwatch.StartNew(); int[] a1 = Array.ConvertAll(s, Int32.Parse); int[] buffer = new int[d]; Array.Copy(a1, 0, buffer, 0, d); Array.Copy(a1, d, a1, 0, a1.Length - d); Array.Copy(buffer, 0, a1, a1.Length - d, d); sw.Stop(); foreach(var num in a1) Console.Write(num + " "); Console.WriteLine(); Console.WriteLine(sw.ElapsedTicks); // 700+ ticks

- JH
indyHarcourt + 0 comments My C# code:

var inString = Console.ReadLine().Split(' '); var size = int.Parse(inString[0]); int d = int.Parse(inString[1]); var inString_temp = Console.ReadLine().Split(' '); List<int> seq = Array.ConvertAll(inString_temp,Int32.Parse).ToList(); int pointer; for (pointer = d; pointer < seq.Count; pointer++) { Console.Write($"{seq[pointer]} "); } for (pointer = 0; pointer < d; pointer++) { Console.Write($"{seq[pointer]} "); }

h276692580 + 5 comments Did anyone consider if we cant alloc a new array to store sorted array, only operate the old array to left rotation?

justin_gries + 0 comments At the very least, you would have to allocate memory to store one integer. The question then becomes what you consider to be important: memory, or run-time, or something in between. If your primary focus is memory, then your solution is just to move EVERYTHING in the array one unit over, multiplied by the number of iterations. (You can mitigate this somewhat by right-shifting if the number of iterations is more than 1/2 the size of the array.) If your focus is time, then just transfer everything to another array, and back again, giving ~ O(2n). A decent in-between (which is what I went with) is to move only the number of elements out that you need to move (max 1/2 n) to another array, shift everything else, then re-insert the moved elements.

rulov_ivan + 0 comments It is not the best solution but it requires only one array:

static void Main(String[] args) { string[] read = Console.ReadLine().Split(' '); int n = int.Parse(read[0]); int d = int.Parse(read[1]); int[] array = new int[n]; array = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse); for(int q=0;q<d;q++) for(int i=0;i<n-1;i++) { swap(array, i,i+1); } for(int y=0;y<n;y++) Console.Write(array[y] + " "); Console.WriteLine(); } static void swap(int[] input, int indexA, int indexB) { int tmpA = input[indexA]; int tmpB = input[indexB]; input[indexA] = tmpB; input[indexB] = tmpA; }

- CT
carlostse + 0 comments Yes. But I think it will slower than

int *swp = new int[n]; memcpy(swp, (const void *)(arr + d), (n - d) * sizeof(int)); memcpy(swp + (n - d), (const void *)arr, d * sizeof(int));

Correct me if I am wrong.

nintendroid + 0 comments [deleted]nintendroid + 1 comment My in-place O(n) solution. No allocation required

template <typename Iterator> static void rotate_left(Iterator begin, Iterator mid, Iterator end) { while (begin != mid && mid != end) { auto it = mid; while (begin != mid && it != end) { std::swap(*begin++, *it++); } if (begin == mid) { mid = it; } } } int main() { int n{}; int k{}; std::cin >> n >> k; std::vector<int> values(n); std::copy_n(std::istream_iterator<int>(std::cin), n, values.begin()); auto mid = values.begin(); std::advance(mid, k); ::rotate_left(values.begin(), mid, values.end()); std::copy(values.begin(), values.end(), std::ostream_iterator<int>(std::cout, " ")); return 0; }

- AA
ArshadAQ + 0 comments Why has everyone ignored this?

ihateyou + 1 comment Is it possible to do the same in C# using only one array (as one array must hold the splitted values and other to place them accordingly) ?

rulov_ivan + 0 comments It is not the best solution but it requires only one array:

static void Main(String[] args) { string[] read = Console.ReadLine().Split(' '); int n = int.Parse(read[0]); int d = int.Parse(read[1]); int[] array = new int[n]; array = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse); for(int q=0;q<d;q++) for(int i=0;i<n-1;i++) { swap(array, i,i+1); } for(int y=0;y<n;y++) Console.Write(array[y] + " "); Console.WriteLine(); } static void swap(int[] input, int indexA, int indexB) { int tmpA = input[indexA]; int tmpB = input[indexB]; input[indexA] = tmpB; input[indexB] = tmpA; }

- 祁
a646608986 + 0 comments 厉害，佩服

whoiscris + 0 comments Thumbs up, for sharp thinking. Complicated my solution before stumbling on the same short solution myself :D

- VA
vamphonephong + 0 comments "A left rotation operation on an array of size n shifts each of the array's elements d unit to the left."

This isn't a correct solution. It's merely masking itself to be a solution. It's taking input and stuffing it pre-ordered into a new array. You should be doing a left rotation on an existing array.

hhariyale + 1 comment move that n-d outside the loop its always same. other then that your solution is best.

- JN
jdnark + 0 comments Not sure what the n-d is to move outside the loop. Thanks for the feedback.

I'm trying to figure the site out to do a test for employment. I keep getting time out so I have been experimenting to see what is causing the times outs. I don't want to fail an employment related challenge b/c of a site timeout.

I find I have to write code that is less and less readable to try and get around the timeout issues.

- N
navrattanocp + 2 comments your time complexity : O(n + n) your space complexity : n

you can optimize it a little bit with :

time complexity : n + d space complexity : d

public static void main(String[] args) { Scanner c = new Scanner(System.in); int n = c.nextInt(); int d = c.nextInt(); int skipPart[] = new int[d]; int j =0; for(int i = 0; i < n; i++) { if(i >= d) { System.out.print(c.nextInt() + " "); } else { skipPart[j] = c.nextInt(); j++; } } for(int i = 0; i < skipPart.length; i++) { System.out.print(skipPart[i] + " "); } }

- JN
jdnark + 0 comments Got it. I'm guessing being judged in a challenge your way of thinking is better -- do the challenge int he fewest steps possible. I really do not think of optimzing the stdin/stdout as they are just mechanism for giving you the data needed and demonstrating the algorithm is correct. I'm guessing if company is viewing my code, they will think with your mindset.

- VA
vamphonephong + 2 comments There are a lot of people solving the problem this way. Reread the problem statement and you'll see that this doesn't do what was asked. There only prints out the input in the order expected after a left rotation d times. The real problem is left rotating an existing array and then print the final content of the array. So what you need to do is read in your input and then store it into an unsorted, unrotated, etc array. Left shift that array, and then print it out from array[0] to array [n].

- N
navrattanocp + 0 comments thanks. Got it.

lilbyrdie + 0 comments That's what I was thinking, too. The easiest solution to the

*expected output*isn't necessarily solving the stated problem. But, that's also the nature of the problems. Perhaps a better problem would be one that simply passed in an array and you had to modify said array in place. That would at least ensure the right problem is being solved.

- MB
bonin_maxime + 0 comments I like this I wish I'd came to this algorithm myself ...

- PM
lewap_ruzam + 1 comment Similarly:

public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int d = sc.nextInt(); int array[] = new int[n]; for (int i=0; i<n; i++) { array[i] = sc.nextInt(); } for (int i=0; i<n; i++) { System.out.print(array[(i+d)%n] + " "); } }

kshtjkmar + 0 comments Great Solution!

aabhasr1 + 0 comments A really good solution. I was unable to figure it out mathematically XD.

camkida + 0 comments very clever, thanks!

unzain + 0 comments What a great hack, akueisara39! Given that the defaulted code that read the elements into an array, I saw myself forced to use additional space.

callmeyesh1 + 0 comments Can someone explain how you came about the formula (i+n-d)? I am not able to understand how that formula is derived?

- VR
werner + 0 comments good logic akueisara. i used similar logic like "(i+n-d)%n" in circular linked list.

cayhan + 0 comments it is just awesome. I want to ask how you think this way, while everybody else is concentrating on different point, your solution is really different and cool :) My understanding is you approach the problem right at the beginning, the only issue is the coming up with this formula "(i+n-d)%n" good thinking akueisara39

ademar111190 + 0 comments It is a greate solution.

I think something similar, but your solution is better.

Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int d = scanner.nextInt() % n; int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = scanner.nextInt(); } scanner.close(); for (int i = d; i < n; i++) { System.out.print(arr[i]); System.out.print(' '); } for (int i = 0; i < d; i++) { System.out.print(arr[i]); System.out.print(' '); } System.out.println();

AmandeepSaxena + 4 comments int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int i,d,k,n,temp,j; cin>>n; int a[n]; for(i=0;i<n;i++) cin>>a[i]; cin>>d; for(i=0;i<n;i++) cout<<" "<<a[(i + (n - d)) % n]; return 0; }

pls let me knw wats wrng in this?

dexter97 + 0 comments [deleted]- MI
Mikeiyan + 0 comments cin >> d; should be after cin >> n;

rajatddjsehgal + 1 comment you need to use vector instead of array for memory allocation at runtime else if you are using array they you have to use dynamic array.

- SS
saishashank65 + 0 comments vector leftRotation(vector a, int d) { int temp; for(int j=0;j

//whats wrong one test case not working(timeout error)

shivamrajawat + 0 comments write a[(i+d)%n] in place of a[(i + (n - d)) % n]

- JM
Wafflenaut + 2 comments My C solution was similar:

int main() { int n; int d; int temp; int *array = (int *)malloc(sizeof(int) * n); scanf("%d", &n); scanf("%d", &d); for(int i = 0; i < n; i++){ temp = i - d; if(temp < 0){ temp = temp + n; } scanf("%d", &array[temp]); } for(int i = 0; i < n; i++){ printf("%d ", array[i]); } return 0; }

[DELETED] + 1 comment [deleted]duc5121991 + 0 comments [deleted]

duc5121991 + 0 comments Hand down! Best solution for me!

david_varela + 1 comment It can be optimized in terms of space if you don't store the whole array, but only the rotated elements. If the elements are 1 2 3 ... 100000, and the number of left rotations is 2, you can save the first two elements (1 and 2) and directly print the rest as soon as you read them. Finally, print the saved ones. The difference in space is from 100000 ints to 2 ints.

AmandeepSaxena + 1 comment what if I have thousand rotation??then I have to store thousands of int?

david_varela + 1 comment no no, if you have 1000 rotations in an array of 30, you have 1000/30 complete rotations (rotations of the whole array) and 1000%30 effective left rotations. So you store only the first 1000%30 elements. Sorry for the initial incomplete explanation, my fault.

AmandeepSaxena + 1 comment appreciated!!bt still don't you think it will require alot memory??even if u will use 1000%30

AmandeepSaxena + 0 comments I think on the place to store those elements it will b more efficient to jst show those elements.

alammdtalib + 0 comments How come you reached to this logic array[(i+n-d)%n], i understood what you did here but, having hard time to understand how did you get to this formula, does it comes with expreince or some mathematical practice i am lacking. Thanks

- NA
akotkarniranjan3 + 0 comments Pure Magic !!!

dexter97 + 0 comments [deleted]dexter97 + 0 comments [deleted]- AG
Arpit682 + 0 comments The logic does it in one loop. Brilliant.

- MW
mgwatt0521 + 0 comments Very creative solution!

- AI
justinimran1994 + 0 comments 3 errors is generating

- AI
justinimran1994 + 1 comment public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int d = in.nextInt(); int[] array = new int[n]; int c=0,i,temp; for(i=0; i

`temp=array[0]; for(i=0; i<n;i++) { array[i]=array[i+1]; } array[n]=temp; c++; for(i=0; i<n;i++) { System.out.print(array[i]); } }`

} }

- SS
iit2015046 + 0 comments I used the same logic but timeout error is coming for the last case.

- SK
sksunilkumar107 + 0 comments what is the issue if i write this way.

- GK
gunakk777 + 0 comments Awesome , this really saves time .Thank You..!!

ishabandi + 0 comments I was thining on the same lines after I got the timeout error. But didn't reach anywhere, I was still using the same number of For loops some how! Thanks a lot!

quint + 0 comments [deleted]- SB
SmrutiBarik + 0 comments So without using an extra array u did it. Basically u dont have an input array.. Great

- SS
Coding_Karma + 0 comments is the array[(i+n-d)%n] is some standard algo?

- SS
ssuryawanshi940 + 0 comments suppose if i enter value of n=5;d=2; then it will accept five numbers not more than that but if i wil not hit the Enter key then it will have been accepting the many values i will hav to take only 5 values not more than that

- JS
seek23u + 0 comments Awesome...

- AN
abhiram_nataraj1 + 0 comments amazing!!

fmcnish + 0 comments ¿This works for you? In my analysis, this does a right rotation instead of a left rotation. Isn't it? You should implement the logic for translate right to left rotations or to invert the direction.

- CM
mouli_3022 + 0 comments Nice

olegcherednik + 0 comments static int[] leftRotation(int[] a, int d) { for (int i = 0, j = a.length - 1; i < j; i++, j--) swap(a, i, j); d %= a.length; if (d > 0) { d = a.length - d; for (int i = 0, j = d - 1; i < j; i++, j--) swap(a, i, j); for (int i = d, j = a.length - 1; i < j; i++, j--) swap(a, i, j); } return a; } private static void swap(int[] arr, int i, int j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; }

- MP
markphan2012 + 0 comments Hi akueisara39 : i appreciate your code as it appears to be out of box solution . but i feel it throws an exception when the number of shift operations is greater than the size(d>n) of the array so just added few lines of code to it .

int[] array = new int[n]; if(d>n) d=d%n; for(int i=0; i array[(i+n-d)%n] = scan.nextInt();

} - MP
maitrey2112 + 2 comments Instead of rotating each element we can just cut the string upto that index and paste(append) it at the end of the string.

A solution for python would be

def leftrotation(a,d): return(a[d:]+a[:d])

- MT
matant + 0 comments beautiful solution!!!

- PK
parthkapil97 + 2 comments but this will not work when d > len(a)

- AN
IronicPythonic + 0 comments Correct, I added this line first to account for cases when d > len(a).

d = d % len(a) if d > len(a) else d

- FZ
fezett + 0 comments true, but the constraints say 1 <= d <= n :)

- NS
niksw7 + 0 comments Here's my solution in Kotlin. I did it using circular LinkedList. data class Node(val value: Int, var nextNode: Node?)

fun main(args: Array) { val (n, d) = readLine()!!.split(" ").map(String::toInt) val list = readLine()!!.split(" ").map(String::toInt) var head = Node(list[0], null) var current = head var rotatedHead = head for (i in 1 until n) { val node = Node(list[i], null) current.nextNode = node current = node if (i == d % n) rotatedHead = node } current.nextNode = head

`current = rotatedHead repeat(n) { print(current.value.toString() + " ") current = current.nextNode!! }`

}

eaperezc + 0 comments genius!

- AS
anshul_sachdeva + 0 comments I liked your approach.But I would like to pin point one thing here as you have been already given an array and N number of rotation.ON that array you have to perform operations.You are changing it while reading from console. please have a look at this and let me know if this can be optimized.

static int[] leftRotation(int[] a, int d) { // Complete this function

`int[] b= new int[a.length]; for(int iLoop=0;iLoop<a.length;iLoop++){ b[iLoop]=a[iLoop]; } for(int iLoop=0;iLoop<a.length;iLoop++){ a[iLoop]=b[(iLoop+d)%a.length]; } return a; } But Really good solution though.`

- AP
pathakavinash58 + 0 comments how did you do that it is amazing...how can you think like that.....

- [U
[deleted] + 0 comments nice explanation genius

- SG
Subhrasanta + 0 comments Brilliant

ShkKiit + 12 comments Neatest code to get this done!!!

int n,d; cin>>n; int a[n]; cin>>d; for(int i=0;i<n;cin>>a[i],i++); d=d%n; for(int i=d;i<n;i++) cout<<a[i]<<" "; for(int i=0;i<d;i++) cout<<a[i]<<" "; return 0;

- RB
rajatbarman + 1 comment awesome :)

ShkKiit + 1 comment Thanks :)

sainimohit23 + 0 comments you deserve my respect sir........ AWESOME

thahimumhassanm1 + 0 comments MASHA ALLAH...good logic...simple nd awesome...thanx,4 sharing this..

- NS
krsoni + 2 comments You didn't actually rotated the array, printing the required answer is not the solution. The rotated array might be of some use later in the actual program and the problem is designed to practice the array rotation. Hope you try to understand.

ShkKiit + 1 comment I understand that. But in this question i was required just to print the rotated form so i did the same. If i was to use the array later on, it wouldn't have been tough to declare a new array and start storing in it using a counter variable. So i kept it simple here just to pass all the test cases :)

- VA
vamphonephong + 0 comments "A left rotation operation on an array of size n shifts each of the array's elements d unit to the left."

That opening problem statement alone means that you need to shift an existing array; not just print the array in the shifted order.

grublob + 0 comments Right

- VP
SuperGogeta + 1 comment I do understand d=d%n but in this instance it isn't necessary, question's constraints says

`1<d<n`

ShkKiit + 0 comments Sometimes coders are extra-careful i guess !

- TS
TimSylvester + 0 comments You're over-complicating things with two loops and C arrays in C++.

`int n, d; cin >> n >> d; vector<int> v((istream_iterator<int>(cin)), istream_iterator<int>()); for (int i = 0; i < n; ++i) cout << v[(i + d) % n] << " ";`

learner_codes + 0 comments splendid :)

- N
narutocas143 + 0 comments please explain the logic thanks in advance

- PK
GIWMCoder + 0 comments [deleted] - KJ
kalpit_jain0407 + 0 comments Thanks.Its a smart way to solve the question

_yash_agarwal_ + 0 comments as neat as it can get! so satisfying!

anoop600 + 0 comments but this is just printing data as required . if u check array then no rotation had occured

Skymyweakness + 0 comments awesome ^_^

atulb7777 + 2 comments int main() {

`int n,d,f,j,i,*ar; cin>>n>>d; ar=new int[n]; for(i=0;i<n;i++){ cin>>ar[i]; } for(i=1;i<=d;i++){ f=ar[0]; for(j=0;j<n-1;j++){ ar[j]=ar[j+1]; } ar[n-1]=f; } for(i=0;i<n;i++){ cout<<ar[i]; if(i<(n-1)){ cout<<" "; } } return 0;`

} test case#8 is showing "terminated due to timeout"! Any suggestions? i am new to this!

- RS
rohan565singh + 2 comments I have the exactly same problem. Did anyone figure out why?

- AB
Alexbrc + 0 comments I don't particularly know what test case 8 is exactly, but I would assume that this test case has set the input parameters of n and d to be very large. If you look at the constraints on n, then you will see that n can be as large as 10,000 and d also can be as large as n. With an approach that manually shifts the array one by one a certain amount of times can lead to a lot of work. Possibly shifting all 10,000 elements to the left 10,000 times racks up to a lot of work. You would have to shift something up to 10,000,000,000 times in this scenario. That is a lot of work and would most likely be the reason the test case times out before finishing.

atulb7777 + 3 comments I did solve it! It was proably beacuse of the nested loops! they take more time to run!

- PS
roGue_warRior + 0 comments which is known as complexity

- NB
noahlbw + 1 comment how did you solve it ?

- PS
roGue_warRior + 1 comment Its easy man i cant figure out the last test case though !!

1.Input an array of size n 2.Input number of rotations as r 3. r=r%n -> it reduces the number of repeatative rotations thus decreasing the complexity of our code . suppose the size of the array is 3 and number of rotations is also 3 then our loop wont run it will simply print the same elements .

- take a temperory variable and store the leftmost element in it i.e a[o]
- Now run the loop from 0 to second last element of the array 6.a[i]=a[i+1] -> shifts the element towards left for eg. for i=0 a[0]=a[1]; it shifts all the elements towards left 7.now simply store the first element in temp variable to the last position.
- steps 4 to 7 for first rotation now while loop will run as per the given number of rotations these steps will be repeated until r becomes 0.
- At last display the elements in the array.

:)

pratik9044536615 + 1 comment Man i have better version of solution. See my code.

vector array_left_rotation(vector a, int n, int k) { rotate(a.begin(),a.begin()+k,a.end()); return a; }

int main(){ int n; int k; cin >> n >> k; vector a(n); for(int a_i = 0;a_i < n;a_i++){ cin >> a[a_i]; } vector output = array_left_rotation(a, n, k); for(int i = 0; i < n;i++) cout << output[i] << " "; cout << endl; return 0; }

- S
shubh_aagman24 + 0 comments chup.. space dedeta kuch to

shockwave97 + 1 comment how did u solve??

- S
shafagh + 1 comment Keep in mind a left rotation of x is equal to (len-x) of righ rotations. Hence, it would be more efficient to the rotation with least amount of "moves".

- C
crystalcode + 0 comments Thats true. I got accepted for test case 8 using right rotation. We need to choose :

If #rotations < (size /2) Use Left Rotation If #rotations > (size /2) Use Right Rotation

- AD
akshayd31 + 5 comments My solution in Python:

n,d = map(int, raw_input().strip().split()) arr = map(int, raw_input().strip().split())

print ' '.join(str(s) for s in (arr[d:] + arr[0:d]))

- PB
polmki99 + 2 comments Very similar to my code. I took the modulus of d but it isn't really necessary because the slice method does it automatically.

n, d = map(int, input().strip().split()) arr = list(map(int, input().strip().split())) d %= n print(*(arr[d:] + arr[:d]))

Xarmanla + 0 comments Looks the same as the one I wrote before looking at the discussion. As a person who programmed bit sliced arrays, I love python.

talktofreeman + 0 comments nd = input().split()

`n = int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) l= [1,2,3,4,5,6,7,8,9] i=0 while i<len(a): print (a[(i+d)%len(a)], end = ' ') i+=1`

NotQuantum + 0 comments arr[0:d] you don't need the 0

- FM
florent_moiny + 1 comment Smart move to slice, hadn't thought about it. One way to improve your code (because I had the same issue): you need to use the generator expression

' '.join(str(s) for s in (arr[d:] + arr[0:d]))

because you applied the

`int`

function to your input. Don't do that and it becomes easier:n,d = map(int, raw_input().strip().split()) arr = raw_input().strip().split() print ' '.join(arr[d:] + arr[0:d])

Also, I wouldn't mind an

`if n == d`

, but that's just my point of view here.- FV
freddie71010 + 0 comments Looks great, my python solution printed an unzipped list.

# separates n and d values into two variables n, d = [int(x) for x in input().split()] # creates list of integers lst = [int(x) for x in input().split()] # From inner most function to outermost============= # creates a list using lst[d:] and combines it with lst[0:d] # unzips list (* = unzips) # prints list print(*(lst[d:]+lst[0:d]))

- CH
christine_e_hill + 0 comments Maybe I am being pendantic, but since the instructions said to "Print a single line of space-separated integers", I thought we were supposed to print them as integers.

So I used:

for n in arr: print n,

Still trying to think of an instance in which this distinction would matter...

- AY
yangAnn + 4 comments I thought my solution is neat. but here are more neat solutions!

n, d = map(int, input().strip().split()) arr = [int(arr_t) for arr_t in input().strip().split()] for _ in range(d): arr.append(arr.pop(0)) print (*arr)

- FV
freddie71010 + 0 comments Great solution!

AffineStructure + 0 comments Hey, I like your solution. A recommendation for the future is if you want to pop the first element, you should use a deque. https://docs.python.org/3/library/collections.html#collections.deque

arr.pop(0) is O(N) while the deque version arr.popleft() is O(1)

AatmanMantri + 1 comment Hey! Can you tell me how does *arr work?

- JY
whtiger + 0 comments good one!

smanne + 1 comment No need of loops, here is my solution in js

function processData(input) { //Enter your code here let linesArray = input.split("\n"); let line1 = linesArray[0].split(' '); let numberOfInt = line1[0]; let numberOfRotations = line1[1]; let integers = linesArray[1].split(' '); array1 = integers.slice(0, numberOfRotations); array2 = integers.slice(numberOfRotations, numberOfInt); console.log(array2.concat(array1).join(' ')); }

djinn999 + 0 comments very nice

oersoy + 1 comment my solution in js

function leftRotation(a,n,d) { var array = []; for (var i = 0; i < n; i++) { array[(i + (n-d)) % n] = parseInt(a[i]); } return array; } function main() { var n_temp = readLine().split(' '); var n = parseInt(n_temp[0]); var d = parseInt(n_temp[1]); a = readLine().split(' '); a = a.map(Number); var result = leftRotation(a,n,d); console.log(result.join(" ")); }

djinn999 + 0 comments A left rotation is just arr.push(arr.shift()) if you use built in array tools

- KP
krunalapatel + 1 comment Solution in Python:

first = input().strip().split(" ") list_length = int(first[0]) rotation = int(first[1]) input_list = input().split(" ") for i in range(rotation): input_list.append(input_list.pop(0)) for i in input_list: print(i,end=" ")

Enrique_Medina + 0 comments The append pop is definitely clever

jonathanvasquez + 0 comments This is my solution in C++, pretty straightforward

int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int size_of_vector; int num_of_rotations; int input; cin>>size_of_vector>>num_of_rotations; vector<int>v1; for(int i=0;i<size_of_vector;++i){ cin>>input; v1.push_back(input); } /*pushes back the first element in vector and deletes the first element(which was added to back) which creates a shift */ for(int i=0;i<num_of_rotations;++i){ int temp=v1.at(0); v1.push_back(temp); v1.erase(v1.begin()); } for(int i=0;i<size_of_vector;++i){ std::cout<<v1.at(i)<<" "; } return 0; }

- PG
pradeep9293 + 3 comments *

*Test Case 8 is failing because of TIMEOUT. Any suggestions ? **int main() {

`/* Enter your code here. Read input from STDIN. Print output to STDOUT */`

int size; int arr[100001];

`scanf("%d", &size); int shift, temp; scanf("%d", &shift); for (int i = 0; i < size; i++) { scanf("%d", &arr[i]); } for (int i = 0; i < shift; i++) { temp = arr[0]; for (int j = 0; j < size; j++) { arr[j] = arr[j + 1]; } arr[size - 1] = temp; } for (int x = 0; x < size; x++) { printf("%d ", arr[x]); } return 0;`

}

- BA
baronov + 1 comment did you ever figure it out? I'm having the same problem in JS

function main() { var n_temp = readLine().split(' '); var n = parseInt(n_temp[0]); var k = parseInt(n_temp[1]); a = readLine().split(' '); a = a.map(Number); //console.log("n is "+n); //console.log("k is "+k); //console.log("a is "+a); var length = n; var arr = a; var newArr = []; var value; var index; for (var i=0; i<length; i++){ value = arr[i]; index = i; for (var v=0; v<k; v++){ index = (index-1); if (index == -1){ index = length-1; if (v==(k-1)){ newArr[index]= value; } } else if (v==(k-1)){ newArr[index]= value; } } } console.log(newArr.join(" ")); }

trevordowdle + 1 comment Finally got it to be performant enough to pass by coming up with a for loop less solution.

let arrLength = line1[0], rotations = line1[1] % arrLength, arr = input[1].split(' '); console.log(arr.splice(rotations).concat(arr.splice(0,rotations)).join(' '));

djinn999 + 0 comments can also do arr.push(arr.shift()) in a loop for amount of rotations needed

AatmanMantri + 1 comment Did you find any solution for this? I'm having the same problem.

trevordowdle + 0 comments See my comment above

148W1A05B1 + 0 comments i also write the same code. Did you get the answer for that problem. Please help me...

Sort 955 Discussions, By:

Please Login in order to post a comment