We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Practice
  • Certification
  • Compete
  • Career Fair
  • Hiring developers?
  1. Practice
  2. Tutorials
  3. Cracking the Coding Interview
  4. Arrays: Left Rotation
  5. Discussions

Arrays: Left Rotation

Problem
Submissions
Leaderboard
Discussions
Editorial

Sort 3904 Discussions, By:

votes

Please Login in order to post a comment

  • Hitscotty
    4 years ago+ 0 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();
    }
    
    338|
    Permalink
  • qzhang63
    4 years ago+ 0 comments

    Python 3

    It is way easier if you choose python since you can play with indices.

    def array_left_rotation(a, n, k):
        alist = list(a)
        b = alist[k:]+alist[:k]
        return b
    
    80|
    Permalink
  • chenyu_zhu86
    4 years ago+ 0 comments

    Python index slicing makes this trivial :D

    def array_left_rotation(a, n, k):
        return a[k:] + a[:k]
    
    28|
    Permalink
  • jhaaditya14
    3 years ago+ 0 comments

    I am getting request timeout for test case 8... anyone with same problem?? or anyone knows the solution??

    24|
    Permalink
  • darkOverLord
    4 years ago+ 0 comments

    I did it this way, in Java

    public static int[] arrayLeftRotation(int[] a, int n, int k) {
            if (k >= n) {
                k = k % n;
            }
            
            if (k == 0) return a;
            
            int[] temp = new int[n];
            
            for (int i = 0; i < n; i++) {
                if (i + k < n) {
                    temp[i] = a[i + k];
                } else {
                    temp[i] = a[(i + k) - n];
                }
            }
            
            return temp;
        }
    
    19|
    Permalink
Load more conversations

Need Help?


View editorial
View top submissions
  • Contest Calendar
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature