Arrays: Left Rotation

  • + 95 comments

    With my solution I used modular arithmetic to calculate the position of the each element and placed them as I read from input.

    for(int i = 0; i < lengthOfArray; i++){
        int newLocation = (i + (lengthOfArray - shiftAmount)) % lengthOfArray;
        a[newLocation] = in.nextInt();
    }
    
    • + 1 comment

      Neat code , thanks Hitscotty !!

      • + 3 comments

        The array is a part of the programming field. There are different topics related to this array destination wedding . The left rotation indicates the rotation of elements in an array. The rotation takes place in left wise. The rotation happens a single element at a time.

        • + 4 comments

          My extremely simple solution.

          Hackerrank - Arrays: Left Rotation Solution

          • + 0 comments

            here is problem solution in Java Python C and C++ programming language. https://solution.programmingoneonone.com/2020/07/hackerrank-arrays-left-rotation-solution.html

          • + 0 comments

            can you explain the code

          • + 0 comments

            can you explain your code

          • + 0 comments

            Great solution

        • + 0 comments

          here is problem solution in java python c++ c and javascript programming. https://programs.programmingoneonone.com/2021/03/hackerrank-arrays-left-rotation-solution.html

    • + 10 comments

      hmm.. I'm surprised that worked for you. This one worked for me:

      str = ''
      
      length_of_array.times do |i|
        new_index = (i + no_of_left_rotation) % length_of_array
        str += "#{array[new_index]} "
      end
      
      puts str.strip
      
      • + 2 comments

        what is the starting value of your i? (i dont know ruby). d=2, n = 10. Because if it is 0, it would be (0+2)%10 = 2. What am I getting wrong?

        • + 1 comment

          The starting value of the i is 0. Looks like correct calculation to me. What result are you expecting?

          • + 0 comments

            ha, yeah i wasn't understanding right! I made it this way, that's why I was confused. rotated[(n+i-d)%n] = a[i]. Which is analogous to yours, but calculating the index in destination. Yours is more clear I think. Thanks!

        • + 1 comment

          are you a mathematician? because i came out with a bit similar answer

          • + 1 comment

            me too

            • + 1 comment

              Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!.

              if you guys want to start your own business. But don't have money to start your business.

              you can start your business at a very low investment, by joining a multi level marketing company .if your want to know how to choose a rught company then click here it is a business which is easy to start and run with very low risk.

              Multi Level Marketing orMLM,

              what does it mean. well it may surprise you but it is something that you already do every day, Multi Level Marketing simply means word-of-mouth advertising,or recommending something to someone. If you take a moment to think about it this is something that we all do on a regular basis, we refer friends to our favorite restaurants, movies and vacation spots.We refer books stores, doctors and any number of products that we like to people we know it's simply part of our nature.So the fact is we are all technically Multi Level Marketer,it's just who we are the difference is most of us don't get paid to do this.But some people do and they get paid very well.As you will learn in a moment they are compensated for far more than just their personal recommendations. for more info click here.

              https://www.networkingmarketingnew.com/">9 tips for multi level marketing In multi level marketing, many people come to earn money. Many people fall into this temptation, they will get a lot of money from here, they will not have to work here at all. You guys, let me tell you that without working here, you cannot earn money anywhere. Friends, let me tell you that

              multi level marketing is a business that is exactly like a mountain. If you want to dig it with a spoon, you will not be able to dig it all, nor will you be able to get it yourself with the help of ax. You will need JCB to find it. Similarly, in multi-level marketing too, you should get lots of tips and tricks, with the help of which you can dig the mountain or multi-level marketing.

              If you work properly in multi-level marketing and keep developing your skills, then you will be able to earn a lot of money from here, but if you keep thinking in multi-level marketing, nothing has been done, and many more You get all the money here, you will waste your time here and you will not be able to earn anything. You have a lot of work here. Now work in the film part time, but for how long you are working, you will have to work with your mind. In multi level marketing, there are some steps which are very important. You have to follow them everyday so that you can go far ahead in multi level marketing. In this post, I will tell you about the steps by doing them completely.You keep reading click here

              • + 0 comments

                HackerRank: Please remove this individual's comment

      • + 2 comments

        why do we need i? Can you please explain?

        • + 42 comments

          Based on current index (i), you need to generate new index. For example: let's say array = [1, 2, 3, 4] and k = 2, then after 2 left rotation it should be [3, 4, 1, 2] => 3 4 1 2 (space separated string output)

          Now let's walk through my algorithm:

          # Initial assignments:
            # array = [1, 2, 3, 4]
            # length_of_array = array.length = 4
            # no_of_left_rotation = k = 2
            # new_arr = Arra.new(length_of_array)
          	# new_arr: [nil, nil, nil, nil]
          
          # NOTE:
            # length_of_array.times do |i|
              # is equivalent to 
            # for(i = 0; i < length_of_array; i++)
          
          # Algorithm to calculate new index and update new array for each index (i):
            # new_index = (i + no_of_left_rotation) % length_of_array
            # new_arr[i] = array[new_index]
          
          # LOOP1:
            # i = 0
            # new_index = (0 + 2) % 4 = 2
            # new_arr[i = 0] = array[new_index = 2] = 3
            # new_arr: [3, nil, nil, nil]
          
          # LOOP2:
            # i = 1
            # new_index = (1 + 2) % 4 = 3
            # new_arr[i = 1] = array[new_index = 3] = 4
            # new_arr: [3, 4, nil, nil]
          
          # LOOP3:
            # i = 2
            # new_index = (2 + 2) % 4 = 0
            # new_arr[i = 2] = array[new_index = 0] = 1
            # new_arr: [3, 4, 1, nil]
          
          # LOOP4:
            # i = 3
            # new_index = (3 + 2) % 4 = 1
            # new_arr[i = 3] = array[new_index = 1] = 2
            # new_arr: [3, 4, 1, 2]
          
          # After final loop our new roated array is [3, 4, 1, 2]
          # You can return the output: 
            # new_arr.join(' ') => 3 4 1 2
          

          Hope that's clear.

          • + 0 comments

            Crystal.

          • + 0 comments

            nice algo

          • + 0 comments

            Great explanation! Thanks.

          • + 0 comments

            I am trying to understand this, but this is the first time I have seen value assignments that involve a val= val= anotherVal
            I am not quite understanding how that is supposed to work, also what is "nil" and its purpose for an array

          • + 0 comments

            Cool....

          • + 0 comments

            Excellent Description!

          • + 1 comment

            if the length of the array is = 3 then it seems it won't work.

            • + 0 comments

              ss

          • + 2 comments
            new_index = (i + no_of_left_rotation) % length_of_array;
            

            seems incorrect. You will see the problem if you test, for example [1,2,3,4,5] and k = 2 .

            I guess would be better:

            new_index = (i + (lengthOfArray - no_of_left_rotation)) % lengthOfArray;
            
            • + 0 comments

              why?

            • + 0 comments

              y ? its not working

          • + 3 comments

            Seems like this algorith only works for small number because when the array is big enough due to long looping period u will have system "timeout"

            • + 2 comments

              I was facing the same problem.I gave several attempts but the issue couldn't be solved. Can you please tell me how to define a loop for a set of array with so many elements as such... :)

              • + 5 comments

                In java8 the problem was in String; You have to use more efficient StringBuilder instead; And of couse use only one loop to iterate over array;

                here is my code snippet:

                StringBuilder output = new StringBuilder();
                	
                	for(int i = 0; i<n; i++) {
                		
                		b[i] = a[(i+k) % n];
                		output = output.append(b[i]).append(" ");
                		
                	}
                
                • + 1 comment

                  Thnx

                  • + 1 comment

                    okay

                    • + 1 comment

                      okay

                      • + 1 comment

                        okay

                        • + 1 comment

                          okay

                          • + 1 comment

                            okay

                            • + 0 comments

                              okay

                • + 0 comments

                  Better to use linked list, so no need to LOOP fully:

                  val z = LinkedList(a.toList()) for(i in 0 until n) z.addLast(z.pollFirst())

                • + 0 comments

                  why it is not working if we are using same array to store modified array i.e. a[i]=a[i+k)%n]

              • + 0 comments

                include

                void reverse(int *str,int length) { int start,end; for(start=0,end=length-1;start

                        }
                

                } int main(){

                  int size,nor;
                   scanf("%d %d",&size,&nor);
                 int *str=(int *)malloc(size*sizeof(int));
                 for(int i=0;i<size;scanf("%d",&str[i++]));
                 reverse(str,size);
                 reverse(str,size-nor);
                 reverse(str+size-nor,nor);
                 for(int i=0;i<size;printf("%d ",str[i++]));
                 return 0;
                

                }

            • + 4 comments
              [deleted]
              • + 2 comments

                its because your solution is O(n^2) with the inner loop. Try and find an O(xn) solution and iterate over the whole array only once.

                • + 1 comment
                  [deleted]
                  • + 1 comment

                    O(n^2) means you have 2 for loops causing a greater time complexity

                    • + 0 comments

                      an inner loop will not cause his program to time out. I don't believe the variable n was ever initialized, so the loop is approaching a value of n that isn't defined.

              • + 0 comments

                static int[] rotLeft(int[] a, int d) { int j,i,p; for(j=0;j

                Check with this you will get what is the mistake ypu did.

              • + 0 comments

                My implementation of this in java didn't have this error.

              • + 0 comments

                use only int

            • + 0 comments

              I was facing the same issue in PHP. My solution worked for 9 out of 10 test cases but timed out on one of them every time. You have to re-write the solution to be less memory intensive. In my case I was using array_shift() which re-indexes the arrays, so for large arrays it uses too much memory. My solution was to use array_reverse() and then array_pop() instead, because those methods don't re-index.

          • + 0 comments

            This Does not suits for all entries if you make the rotation to more than 4 its fails

          • + 0 comments

            Brilliant explanation!

          • + 0 comments

            good explanation..working fine.

          • [deleted]
            + 0 comments

            nice algo...easy to understand ...thank u soo much

          • + 0 comments

            Adbsolute geeky, How did it appeared to your mind ?

          • + 1 comment

            How to think like this ? Once the code is there I know its easy to understand.I want to know how did you know to use modulous and how did you come up thinking that logic ?

            thanks in advance.

            • + 1 comment

              Have you ever heard about Data Structure ? because if you do , you would probably heard about circular array.

              I was able to solve the question because I'm knew about circular arrays , we use % + size of array to create a cirural array , then all you need to do is to complete the puzzle to solve the problem.

              check this video, https://www.youtube.com/watch?v=okr-XE8yTO8&t=773s

              • + 0 comments

                This is super helpful, thanks so much for sharing!

          • + 0 comments

            cool

          • + 0 comments

            really run ?

          • + 1 comment

            Great solution. Any tips on how to know if you need to use modulus in your algorithm? I solved this problem using 2 for loops...

            • + 4 comments

              I figured it out by saying, I don't need to loop through this array over and over to know what the final state of the array should be. What I need to figure out is what the first element of the new array will be after I've rotated X amount of times. So if I divide the number of rotations (X) by the length of the array (lenArr) I should get the amount of times the array has been fully rotated. I don't need that, I need what the first element will be after this division operation. For that I need the remainder of that divison (the modulus). This is because after all of the full array loops are done, the remaining rotations determine what the first element in the new array will be.

              So you take that remainder (modulus) and that's the first element's index in the old array. For example, 24 rotations in a 5 element long array means that the first element in the new array is in the 4th index of the old array. (24 % 5 = 4)

              So rotate through [3, 4, 5, 6, 7] 24 times and the first element will be 7. So just take that and put it before the other elements. ([7. 3, 4, 5, 6])


              Another good tip is always look for repeating patterns. It's a sign that you can simplify your code. The for loop method is just repeating the state of the array over and over: [3, 4, 5, 6, 7] [4, 5, 6, 7, 3,] [5, 6, 7, 3, 4,] [6, 7, 3, 4, 5,] [7, 3, 4, 5, 6,] [3, 4, 5, 6, 7] [4, 5, 6, 7, 3,] [5, 6, 7, 3, 4,]...

              You only really need to know what's happening in the final few rotations, after the last full loop.

              • + 0 comments

                great explanation!

              • + 0 comments

                thank you. this is my aha moment. :)

              • + 0 comments

                Superb explanation, now I jnow why Data Structures are imp.

                Your approach shows how things should be done. I ll be soon implementing this on Python and post the same, dats gonna help many developers

              • + 0 comments

                Great analysis !

          • + 0 comments

            Nice explanation. helped me a lot. Thanks You

          • + 0 comments

            Awesome Explanation....Tq

          • + 0 comments

            thankyou so much, it helped a lot. but can you please tell how did you think about the new index position. what did you think?

          • + 0 comments

            Great explanation!Thanks

          • + 0 comments

            great way of explaining.big thank!

          • + 0 comments

            Nice algo..

          • + 0 comments

            Good Solution.

          • + 1 comment

            simple is peace

            return arr[d:] +arr[0:d]

            • + 0 comments

              but im getting timed out if i do like this for 2 test cases

          • + 0 comments

            Greatest explanation so far. Thanks!

          • + 0 comments

            Well Explained !!

          • + 1 comment

            Can you please also tell me the logic of right rotation .

            • + 1 comment

              Here is the answer for right rotation:

                   def rightRot(a,d):
                      return a[d+1:]+a[:d+1]
              
              • + 1 comment

                can you explain this please

                • + 0 comments

                  This is my code and it passes all the test cases.

                  include

                  using namespace std;

                  int main() { int n,d; int a[n]; for(int m=0;m>a[m]; } cin>>d; for(int i=1;i<=d;i++) { int k=0; for(int j=1;j

                  return 0; }

          • + 0 comments

            Thanks for the explanation

          • + 0 comments

            great explaination..

          • + 0 comments

            The only solution that explained it fully. Very clear.

          • + 0 comments

            Amazing you are a nice explainer . I impressed.

          • + 0 comments

            Very clear. Great Explanation

          • + 0 comments

            what a beautiful logic too good.

          • [deleted]
            + 0 comments

            great.

          • + 0 comments

            Amazing explanation, thanks :)

          • [deleted]
            + 0 comments

            thanks

          • + 0 comments

            The question your algorithm answers is index of the element that should be in index i; while the other guy answered the final index of the index i.

          • + 0 comments

            Thanks so much for your explanation!

          • + 0 comments

            Awesome explanation!!!! Thank you so much!!

          • + 0 comments

            first of all nice explaination brother and my question is how did you come up with this solution ?

        • + 0 comments

          i is a variable used to iterate through the loop, it generally represents the index of the array that is being referenced on a particular iteration of the loop.

      • + 0 comments

        Your code if for right rotation, and the explanation gave you right answer as the size was 4 and k =2 , so no matters you do left/right you will get same. For left it will be int newLoc= (n +(i-k))%n;

      • + 0 comments

        Array = {1,2,3,4,5} d = 4 Dosen't work for me

        My Code :

        for (int i = 0; i < a.Length; i++) { position = Math.Abs((i + (a.Length - d))% a.Length); newArray[position] = a[i]; }

      • + 0 comments

        nice algorithm manish

      • + 0 comments

        This answer is true for right shifting, for left shifting test cases are failing.

        for(int i = 0; i < lengthOfArray; i++){ int newLocation = (i + (lengthOfArray - shiftAmount)) % lengthOfArray; a[newLocation] = in.nextInt(); }

        This is correct answer for left shifting.

      • + 0 comments

        a.rotate(d) is simplest solution in ruby

      • + 0 comments

        Great... Your formula worked for me in JS:

        for (var i = 0; i < array.length; i++) {
        var newPos = (i + no_of_left_rotation) % array.length;
        newArray[i] = array[newPos];
        }

        Thanks a bunch mate :).

      • + 0 comments

        It did not work in my case.

    • + 3 comments

      I guess the logic fails if the input is as follows: 5-n 6-d 1 2 3 4 5

      • + 0 comments

        According to given constraint : 1 <= d <=n, d will not exceed n

      • + 0 comments

        Even if there was no constraint, you could just do: k % n, and then apply the same logic.

    • + 4 comments

      The question asks to shift a fully formed array, not to shift elements to their position as they're read in. Start with a fully formed array, then this solution does not work.

      • + 0 comments

        thats what me too thinking of..was wondering why the logic writte here was arranging the array on read...

      • + 1 comment

        That's exactly the point of the exercise. You have to rotate an already existing array.

        • + 0 comments

          Correct!

      • + 0 comments

        I noticed that right away. If the point was to produce printed output, then this is fine (and a lot of analysis works backward from output). But, as stated, one is supposed to shift an array, so this missed it.

      • + 0 comments

        this could easily be modified though by creating another array of the same size:

        vector b(n); for(int i = 0; i < n; i++) { b[i] = a[(i+k) % n]; } return b;

    • + 0 comments

      I had the same idea! Just find the starting point of the array with the shift and count on from there, taking modulo and the size of the array into account.

    • + 1 comment

      (i + shift) % lenght Should be enough

      • + 0 comments

        Except that describes a right shift, and specification says a left shift. You might consider left shift to be negative shift, in which case you are correct mathematically, but I'd feel much more comfortable keeping the whole calculation in positive territory.

    • + 4 comments

      modular arithmetic is cool. I solved that way too

      for idx in range(0, _size):
        indexes[(idx - shift + _size) % _size] = _list[idx]
      
      • + 1 comment

        Can you please explain how that works?

        • + 2 comments

          image

          • + 0 comments

            Hello, where did this solution from? what should I study to be able to come up with solutions like this?

          • + 1 comment

            I love your writing, so neat!

            • + 0 comments

              Good solution

      • + 6 comments

        Looks a lot like my C# solution:

        static int[] Rotate(int[] a, int n) {
            n %= a.Length;
            var ret = new int[a.Length];
            for(int i = 0; i < a.Length; ++i) {
                ret[i] = a[(i + n) % a.Length];
            }
            return ret;
        }
        
        • + 0 comments

          Perfect solution. Thanks for sharing

        • + 1 comment

          Nice solution. You dont need:

          n %= a.Length;
          
          • + 1 comment

            This line usefull when n >= a.Length

            • + 0 comments

              No it isn't. (i + n) % a.length and (i + n%a.length) % a.length are the same thing. It's only useful for the case where n is close to int maximum so that i + n overflows.

        • + 0 comments

          Nice

        • + 0 comments

          Could you please explain your solution..?

        • + 1 comment

          Here's another slightly different solution. I'm assuming it would be less performant, since it uses List and then converts it to Array, but I'm not sure how much more so.

          static int[] rotLeft(int[] a, int d) {
              var result = new List<int>();
          
              for (int i = d; i < (a.Length + d); i++)
              {
                  result.Add(a[i%a.Length]);
              }      
          
              return result.ToArray();
          }
          
          • + 0 comments

            `what about this?

            static int[] rotLeft(int[] a, int d) {

                int[] temp = new int[a.Length];
                int hg = 0;
                for (int i = d; i < (a.Length+d);i++)
                {
                    temp[hg] = a[i%a.Length];
                    hg++;
                }
                return temp;`
            
        • + 0 comments

          Awesome!

      • + 3 comments

        I agree modular arithmetic is awesome. But, simple list slicing as follows solves too ;)

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

        • + 0 comments

          I agree

        • + 0 comments

          Oh my goodness! You are the best!

        • + 0 comments

          Agreed

      • + 0 comments
        def rotLeft(a, d):
            return a[d:] + a[:d]
        
    • + 2 comments

      what if newLocation becomes negative

      • + 0 comments

        then you send it to the end of the array

      • + 0 comments

        The modulus operation always returns positive. If, as in Java, it really does remainder, rather than the mathematical modulus, it can return negative. So, depends on which language.

    • + 2 comments

      What if lengthOfArray < shiftAmount? I think you should use abs value

      • + 0 comments

        there is a constraint that says there wont be negatives so it should be fine. if it wasn't given then use abs.

      • + 0 comments

        You deal with lengthOfArray < shiftAmount by using:

        shiftAmount = shiftAmount % lengthOfArray;
        

        If the array length is 4, and you're shifting 6, then you really just want to shift 2.

        The constraints say that shiftAmount will always be >= 1, so you don't have to worry about negative numbers.

    • + 0 comments

      Aweosme !!!

    • + 10 comments

      pretty simple in js:

      a.splice(k).concat(a.slice(0, k)).join(' ')
      
      • + 0 comments

        even simpler is a.splice(k).concat(a).join(' ')

      • + 1 comment

        what does a represent?

        • + 0 comments

          The array of initial values.

      • + 2 comments

        Did something similar in C#..

        using System;
        using System.Collections.Generic;
        using System.IO;
        using System.Linq;
        class Solution {
            
            static string rotate(int rot, int[] arr)
            {
                string left = string.Join(
                    " ", arr.Take(rot).ToArray()
                );
                string right = string.Join(
                    " ", arr.Skip(rot).ToArray()
                );
                return right + ' ' + left;
            }
        
            static void Main(String[] args) {
                string[] tokens_n = Console.ReadLine().Split(' ');
                int n = Convert.ToInt32(tokens_n[0]);
                int k = Convert.ToInt32(tokens_n[1]);
                string[] a_temp = Console.ReadLine().Split(' ');        
                int[] a = Array.ConvertAll(a_temp,Int32.Parse);
        
                // rotate and return as string
                string result = Solution.rotate(k, a);
                // print result        
                Console.WriteLine(result);
            }
        }
        
        • + 2 comments

          Or you can one line it with LINQ

          Console.Write(string.Join(" ", a.Skip(k).Concat(a.Take(k)).ToArray()));

          • + 1 comment

            While it is definitely elegant looking with a single line of code, how many times will this iterate over the array when performing 'skip', 'take' and 'concating' them? In other words, what's the complexity of this algorithm?

            • + 0 comments

              O(n)

          • + 0 comments

            Any resources that explain how this works? I definitely see that it works, but say k is 5 in the first example and the array is 12345, it looks like we're skipping the whole array, then concatenating that whole array back to it with Take(5). What am I missing? Thank you for your time.

        • + 5 comments

          Can any one please tell me why the below code is timing out for large data set:

          for(int j=0;j<k;j++)
                  {
                  for(int current=n-1;current>=0;current--)
                  {
                     if(current!=0)
                     {
                         if(temp!=0)
                         {
                           
                      a[current-1]= a[current-1]+temp;
                             temp= a[current-1]-temp;
                             a[current-1]=a[current-1]-temp;
                         }
                         else
                         {
                             temp=a[current-1];
                             a[current-1]=a[current];//for the first time
                            
                         }
                      
                     
                     }
                      else//when current reaches the first element
                      {
                          a[n-1]=temp;
                          
                      }  
                  }
                      
                  }
                  Console.WriteLine(string.Join(" ",a));
          
          • + 2 comments

            mine is also a brute force approach but it worked check it out if it helps you

            import java.io.*;
            import java.util.*;
            import java.text.*;
            import java.math.*;
            import java.util.regex.*;
            
            public class Solution {
            
                public static int[] arrayLeftRotation(int[] a, int n, int k) {
                   int temp,i,j;
                    for(i=0;i<k;i++){
                        temp=a[0];
                        for(j=1;j<n;j++){
                           a[j-1]=a[j]; 
                        }
                        a[n-1]=temp;
                    }
                  
                    return a;
                }
                
                public static void main(String[] args) {
                    Scanner in = new Scanner(System.in);
                    int n = in.nextInt();
                    int k = in.nextInt();
                    int a[] = new int[n];
                    for(int a_i=0; a_i < n; a_i++){
                        a[a_i] = in.nextInt();
                    }
                  
                    int[] output = new int[n];
                    output = arrayLeftRotation(a, n, k);
                    for(int i = 0; i < n; i++)
                        System.out.print(output[i] + " ");
                  
                    System.out.println();
                  
                }
            }
            
            • + 0 comments
              int main(){
                  int n; 
                  int k; 
                  int temp1, temp2;
                  scanf("%d %d",&n,&k);
                  
                  int *a = malloc(sizeof(int) * n);
                  for(int a_i = 0; a_i < n; a_i++){
                     scanf("%d",&a[a_i]);
                  }
                  k = k %n;
                  for(int a_i = 0; a_i < k; a_i++){
                      temp1 = a[0];
                      for(int i = 1; i < n; i++){
                          a[i-1] = a[i];
                      }
                      a[n-1] = temp1;
                  }
              
                  for(int a_i = 0; a_i < n; a_i++){
                     printf("%d ", a[a_i]);
                  }
                  
                  return 0;
              }
              

              my code is the same as yours but i still time in test case 8, why is that?

            • + 0 comments

              You're not wrong but this solution is inefficient. You're solving it in O(((n-1) * k) + 2n). The solution below is in O(2n).

              private static void solution(int size, int shift, int[] arr) {
              
              		int count = 0;
              
              		for (int i = shift; i < size; i++) {
              			System.out.print(arr[i]);
              			System.out.print(" ");
              			count++;
              		}
              
              		count = 0;
              
              		for (int i = size - shift; i < size; i++) {
              			System.out.print(arr[count]);
              			if (i != size - 1)
              				System.out.print(" ");
              			count++;
              		}
              	}
              
          • + 2 comments

            I got a timeout error for TC#8 and #9 for the same logic in Python :(

            • + 1 comment

              i got time out for tc#8 in c why??????

              • + 0 comments

                Iterate over array only once

            • + 0 comments

              No loops. Just split and reconnect. def rotLeft(a, d): b = [] b = a[d:len(a)] + a[0:d] return b

          • + 1 comment

            Because it is O(n*k), if you have a big n and a big k, it could timeout. See if you can think of an algorithm that would visit each array element only once and make it o(n). Also, is there any optimization you can make? For example: if k is bigger than n, then you don't need to do k rotations you just need to do k % n rotations and k will be much smaller, smaller than n. Example:

            [ 1, 2, 3, 4, 5 ]

            K=2, K=7=(1*5)+2, K=12=(2*5)+2, they are all equivant, leading the array to be:

            [3, 4, 5, 1, 2]

          • + 1 comment

            My Solution :

            public static int[] arrayLeftRotation(int[] a, int n, int k) {
                  int[] b = new int[n];
                    for(int i=0;i<n-k;i++){
                        b[i] = a[k+i];
                    }
                   int l = 0;
                    for(int i=n-k;i<n;i++){
                        b[i] = a[l++];
                    }
                   return b; 
                    
                    
                }
            
            • + 1 comment
              [deleted]
              • + 1 comment

                with one for loop i have subitted the code

                • + 0 comments

                  Can I ask how you managed that?

          • + 0 comments

            nested loop.... you should use only one loop

      • + 0 comments

        Nice one! Didn't even think of that

      • + 1 comment

        in an actual interview they will ask you not to use splice or slice. had that happen ti me.

        • + 0 comments

          Yes, no inbuilt functions can be used. They ask that in interviews.

      • + 0 comments

        pretty elegant solution

      • + 1 comment

        indeed, forgot that end goes through the end of a sequence, so here is my solution

        function rotLeft(a, d) {
            const index = d % a.length;
        
            return [...a.slice(index), ...a.slice(0, index)];
        }
        
        • + 0 comments

          function rotLeft(a, d) { return [...a.slice(d), ...a.slice(0, d)] }

    • + 0 comments

      nice one

    • + 0 comments

      i think that the new location = ((i + Shift)) % lenght of array

    • + 0 comments

      godlike solution.

    • + 0 comments

      this doesnt work if you shift by 3.

    • + 1 comment

      Spoiler! You can do it even simpler: rotated[i] = a[(i + k) % n]. Also spoilers should be removed from the discussion or the discussion should only be available after solving. I will complain about this until its changed :P

      • + 0 comments

        wouldn't then space complexity be O(n)

    • + 0 comments

      Very nice.

    • + 0 comments

      @hitscotty what brought you to modular arithmetic for this solution?

    • + 0 comments

      what if shiftAmount is greater than length of array

    • + 0 comments

      your solution is cool but if you have an array as input then you are in trouble bcoz in that case you have space complexity of O(n) as you need an another array to store element in new place.. think..

    • [DELETED] + 1 comment
      [deleted]
      • + 1 comment

        why do you use this approach if in a realtime env. this wouldn't be correct as you are just given the function to complete.

        • + 0 comments

          rishabh10 can u please explain ??

    • + 0 comments

      It is not following the instructions. Sorry.

    • + 0 comments

      Great Logic!! Thank you so much!!

    • + 0 comments

      can u pls expalin what is shiftAmount???

    • + 2 comments

      Hey @Hitscotty! What will be the newLocation if you wish to do a right rotation?

      • + 0 comments

        right rotation : b[i] = a[(i-k)%n]

      • + 1 comment

        Right rotation can be done by changing the '-' sign.. Use [(n+k+i)%n] one in scan function.. and also it is useful to keep in mind ,1 right roation=(n-1)left rotation..

    • + 0 comments

      Hey, guys
      Here is a solution based on modular arithmetic for the case when k > n:

      new_index = (n + i - abs(k-n)) % n
      

      (note: n - abs(k-n) can be collapsed to a single number)

    • + 0 comments

      This only work when you read directly from input. But in the question they have asked to do rotation operation only on Array, so your solution cannot be used for this problem.

    • + 0 comments

      I understand how this works, but how did you think of it?

    • + 0 comments

      This will also fail when my shiftAmount = 7 and lengthOfArray = 3, in short lengthOfArray is less than shiftAmount. In this case we can use Math.abs(). for(int a_i=0; a_i < n; a_i++){ int new_index = Math.abs((a_i + (lengthOfArray - shiftAmount))) % lengthOfArray ; a[new_index] = in.nextInt(); }

    • + 0 comments

      Superb man.....

    • + 1 comment

      That's nice but its kinda cheating :)

      • + 1 comment

        It's not cheating exactly. Using the same method you can even rotate the array, instead of printing the array just give the values of the array to a new array.

        • + 0 comments

          I was nitpicking, I thought of the same soln at first but then changed my mind;

          As the question was GIVEN an array ..so if this was an interview there is this constraint that your array is already populated with the elements.

          btw r u 14 ? its great to see my young indian frnds indulging in programing

    • + 0 comments

      Well done! I did it by finding the correct number for the index, rather than the new position of a given number:

      for (int i =0; i < n; i++){
          int num = a[((n + k) % n + i) % n];
          System.out.print((num) + " ");
      }
      
    • + 0 comments

      very good, thanks!!!

    • + 1 comment

      can u please elaborate some more about your code as i dont have much knowledge about modular maths

      • + 0 comments

        Have I used modulo in my code? I really forgot what have I written if you could show me the code then I can elaborate :)

    • + 0 comments

      the requirement is to take an array and left rotate the array d times. Your solution returns the correct result, but takes an integer one at a time.

    • + 0 comments

      what is in.nextInt() here.

    • + 0 comments

      Thanks for sharing this code it really helpped. I felt the constraints were to be includes by ifstatements but after viewing your code I was able get it. I have a small suggestion, would it improve the code if one were to seperate the (LengthOfArray - ShiftAmount) part into a variable and then reuse it since its kind of a constant value. Once again kudos.

    • + 0 comments

      what is the use of in.nextInt(),will u plz explain me.

    • + 0 comments

      Neat code, the only possible optimization is extra space used. even for a single rotation on say 1 million elements, the algo is greedy on space and will create 1 million auxilary elements.

    • + 0 comments

      Brilliant

    • + 0 comments

      what is in.nextInt() which language is that did you create another scanner object of in can you be more specific?

    • [deleted]
      + 0 comments

      Very celever! thanks.

    • + 0 comments

      reverse it

      arr1=a[0:d]

      arr2=a[d:]

      return arr2+arr1

    • + 0 comments

      It's easy when you directly read them from system input. Try to make it work on already stored array. That's what problem statement says. It gets tricky and interesting after that to solve it in o(n) without extra memory.

      i.e. // Complete roLeft function

      My solution

      private static int getIncomingIndex(int index, int rotations, int length) {
          if(index < (length - rotations)) {
              return index + rotations;
          }
          return index + rotations - length;
      }
      
      // Complete the rotLeft function below.
          static int[] rotLeft(int[] a, int d) { 
                 int rotations = d % a.length;
      
          if(a.length == 0 || a.length == 1 || rotations == 0) {
              return a;
          }
      
          if( a.length % 2 == 0 && a.length / 2 == rotations) {
              for(int i =0 ; i < a.length / 2 ; i++) {
                  swap(a, i, i + rotations);
              }
          } else {
              int count = 0;
              int i = 0;
              while(true) {
                  int dstIndex = getIncomingIndex(i, rotations, a.length);
                  swap(a, i, dstIndex);
                  i = dstIndex;
                  count++;
                  if(count == a.length - 1) {
                      break;
                  }
              }
          }
          return a;
      }
      
    • + 1 comment

      nice code tq

      • + 0 comments

        Welcome.

    • + 1 comment

      The part I'm missing here is why use a loop (O(n)). Can't you take the array and find the effective rotation based on the shift amount (using the same modular arithemetic you're doing? (Which is now O(1) since the length of the array is a property)

      function rotLeft(a, d) {
      
        //calculate effective rotation (d % a.length)
        let effectiveRotation = d % a.length;
      
        // split a at index of effective rotation into left and right
        let leftPortion = a.slice(0, effectiveRotation);
        let rightPortion = a.slice(effectiveRotation); 
      	
        // concat left to right
        return rightPortion.concat(leftPortion)
      }
      
      • + 0 comments

        Can you explain how this is O(1) ? Please read about how slice and concatenation implemented in the language you are using. Also it uses extra memory.

    • + 0 comments

      vera level..!

    • [deleted]
      + 0 comments

      Why would you loop for every element when in essence the rotation operation is nothing but just a rearrangement of the array elements in a specified fashion?

    • + 0 comments

      helps a lot

    • + 0 comments

      Verry Good!

    • [deleted]
      + 0 comments

      I saw this answer in stackoverflow too.. Please be kind enough to explain this.
      Thanks

    • + 0 comments

      Tried a different approach

      def rotLeft(a, d): return reversed(list(reversed(a[:d])) + list(reversed(a[d:])))

    • + 0 comments

      But isn't the whole point that you are not placing them as they come, the array is pre-populated and then rotate it. My solution is O(dn), not sure if there is anything better. Clearly I am not an algorithm guy (anymore)!

      for (int i = 0; i < d; i++) { int pop=a[0]; //shift left for (int j = 1; j < a.length; j++) { a[j-1] = a[j]; } //push a[a.length-1]=pop; }

    • + 1 comment

      Excellent !!! I am new to problem solving. I had solved it via normal shifting using one for loop and one while loop. How did you arrive at this kind of solution?? Little bit of explanation as what you thought while solving this would help a lot.

      Thanks.

      • + 0 comments

        I don't see my submission in the discussion board. Are you reviewing my solutions?

    • + 0 comments

      How can I do this in C++?

      a[newLocation] = in.nextInt();

    • + 0 comments

      If the number of rotations are greater than array length (I know it's less than array length which is given in the question, let us assume), then how would this formula change? BTW That's a great way to get the array indices without having to traverse the whole array

    • + 0 comments

      Interesting take on the problem!

      I'm just mentionning this for completeness' sake but not actually solving the problem as asked, which is to write a separate function :)

      Also, a follow-up question might be "improve your function so that it rotates the array in-place"

    • + 0 comments

      Nice solution! Thanks for sharing :)

    • + 0 comments

      How do you people come up with such optimization? my mind doesn't seem to work :(

    • + 0 comments

      I was thinking to do the same but thought not gonna do this with arithmetic so I just looped twice.

      let result = [];
      for(let i = shiftAmount; i < array.length; i++){
          result.push(array[i]);
      }
      for(let i = 0; i < shiftAmount; i++){
          result.push(array[i]);
      }
      return result;
      
    • + 0 comments

      sorry to bother..i'm having trouble calculating for these values.. array length=5, no._of rotations=7.

      if i take i=0 i=(0+(5-7)%5); which is equal to -2??

      what am i doing wrong?

    • + 0 comments

      Great solution! It's possible to simplify that by finding new position as:

      newPos = (i - d)%length
      
    • + 0 comments

      optimise by returning array if lenght and rotations are same

    • + 0 comments

      what if shift amount is negative?

      for(int i = 0; i < lengthOfArray; i++){
      
              int newLocation = (i + (lengthOfArray - abs(shiftAmount))) % lengthOfArray;
              a[newLocation] = in.nextInt();
      }
      
    • + 0 comments

      In js, I tried a different approach. In node.js, it has no difference in performance when it is compared to other approach.

      function rotLeft(a, d) {
          let i = 0, j = i + d;
          let arr = [];
      
          while (i < a.length) {
              if (j < a.length) {
                  arr[i] = a[j];
                  j++;
              } else {
      		 j = 0;
              }
           i++;
          }
          return arr;
      }
      
    • + 0 comments

      my one liner solution

      return a[d:] + a[:d]

      where a is the arraya and d is the number of rotation

    • + 0 comments

      static int[] rotLeft(int[] a, int d) { int size=a.length; int [] arr=new int[size]; for(int i=0;i

      }
      
    • + 1 comment

      I think there is no need of any maths or what you did. Well what i do is down below, more simple and works for all test cases.

      #a = given_array
      #d = given number of left rotations to be done
      b = []
      b.append(a[d:])
      b.append(a[:d])
      
      • + 1 comment

        Try to do it without slicing.

        • + 0 comments

          that will help you to learn how to code.

    • + 0 comments

      python implementation:

      def rotLeft(a, d):
         return [a[i%len(a)] for i in range(d,d+len(a))]
      
    • + 0 comments

      def rotLeft(a, d): n=d%len(a) return (a[n:]+a[:n])

      These two lines are enough .

    • + 0 comments

      This is exact logic what i came up with, but had a hard time implementing the same. Thanks a lot !

    • + 0 comments

      can you explain the purpose of modulus operation and explain the formula please???

    • + 0 comments

      vector rotLeft(vector a, int d) { int temp; for(int i=0; i

    • + 1 comment
      [deleted]
    • + 0 comments

      Check for the newest solution, simple and sober for noobs too.

    • + 1 comment

      how did you come up with this solution? Are you a mad genius or had knowledge of this concept and applied it

      My mind is actually blown

      • + 0 comments

        happy that you got the code.

    • + 0 comments

      Simple, elegant and efficient!

      Great job!

    • + 0 comments

      Really perfect solution! Thank you for sharing!

    • + 0 comments

      one line solution with Python 3:

      return(a[d:]+a[:d])
      
    • + 0 comments

      What happens if the shiftAmount is larger than the length of the array? I do not think that will work in languages in which modulo can return a negative number.

    • + 0 comments

      include

      int main() { int a[50],n,i,d,j,temp; scanf("%d %d",&n,&d); for(i=0;i=1&&d<=n) { while(d!=0) { temp=a[0]; for(i=1;i

    • + 0 comments

      Is this cheating?

      function rotLeft(a, d) {

       d = d % a.length;
      
       if(d){
             for(let i=0; i<d; i++) a.push(a.shift());
       }
      
       return a;
      

      }

      d => so that I avoid unnecessary shifts
      

      Eg: 5 elements when rotated 12 times it's the same as rotating 2 times

      Hence instead of rotating 12 times we only rotate 2 times

      And if it has to be rotated 10 times it's the same as not rotating at all so return the original array

    • + 1 comment
      [deleted]
    • + 0 comments

      This went over my head

    • + 0 comments

      while(d!=0) { int temp=a.get(0); a.remove(0); a.add(temp); d--; } return a;

    • + 0 comments

      @Hitscotty How do you came up with this solution? Its good thing to learn this approach.

    • + 0 comments

      you could also do just (i + shiftAmount) % lengthOfArray

    • + 0 comments

      https://medium.com/p/b74dff840071