Hacker Rank: Array left rotation





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







14












$begingroup$


This code is to solve the Hacker Rank problem array left rotation.



A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].



Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers.



public static int rotLeft(int a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = 0;
temp = a[0];
for (int intK = 0; intK < a.Length; intK++)
{
a[a.Length - (a.Length - intK)] = a.Length - 1 == intK ? temp : a[a.Length - (a.Length - (intK + 1))];
}
}
return a;
}
static void Main(string args)
{
string nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
int result = rotLeft(a, d);
Console.WriteLine(string.Join(" ", result));
}


This program works fine, but it takes too long with some examples. How can I improve it?










share|improve this question











$endgroup$








  • 6




    $begingroup$
    The best code is no code at all. Do you actually need to rotate the array, or just print the elements in rotated order? Because if that’s the case then you can save a whole lot of copying around.
    $endgroup$
    – Konrad Rudolph
    Mar 4 at 12:45










  • $begingroup$
    From O(n^2) to O(n): int n = d % a.Length; var b = a.Skip(n).Concat(a.Take(n)).ToArray();. You can always get rid of the lazy enumerable when its too slow.
    $endgroup$
    – Caramiriel
    Mar 4 at 13:26






  • 7




    $begingroup$
    @Caramiriel, you've got the wrong box. The one for answers is further down the page.
    $endgroup$
    – Peter Taylor
    Mar 4 at 14:32






  • 1




    $begingroup$
    @Caramiriel this isn't O(n) because Skip is not clever... as far as I know it iterates the collection to skip the items.
    $endgroup$
    – t3chb0t
    Mar 4 at 16:00






  • 4




    $begingroup$
    @t3chb0t Even if it goes through the array twice, 2n, or 200n for that matter, is still O(n)
    $endgroup$
    – TemporalWolf
    Mar 4 at 18:09


















14












$begingroup$


This code is to solve the Hacker Rank problem array left rotation.



A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].



Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers.



public static int rotLeft(int a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = 0;
temp = a[0];
for (int intK = 0; intK < a.Length; intK++)
{
a[a.Length - (a.Length - intK)] = a.Length - 1 == intK ? temp : a[a.Length - (a.Length - (intK + 1))];
}
}
return a;
}
static void Main(string args)
{
string nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
int result = rotLeft(a, d);
Console.WriteLine(string.Join(" ", result));
}


This program works fine, but it takes too long with some examples. How can I improve it?










share|improve this question











$endgroup$








  • 6




    $begingroup$
    The best code is no code at all. Do you actually need to rotate the array, or just print the elements in rotated order? Because if that’s the case then you can save a whole lot of copying around.
    $endgroup$
    – Konrad Rudolph
    Mar 4 at 12:45










  • $begingroup$
    From O(n^2) to O(n): int n = d % a.Length; var b = a.Skip(n).Concat(a.Take(n)).ToArray();. You can always get rid of the lazy enumerable when its too slow.
    $endgroup$
    – Caramiriel
    Mar 4 at 13:26






  • 7




    $begingroup$
    @Caramiriel, you've got the wrong box. The one for answers is further down the page.
    $endgroup$
    – Peter Taylor
    Mar 4 at 14:32






  • 1




    $begingroup$
    @Caramiriel this isn't O(n) because Skip is not clever... as far as I know it iterates the collection to skip the items.
    $endgroup$
    – t3chb0t
    Mar 4 at 16:00






  • 4




    $begingroup$
    @t3chb0t Even if it goes through the array twice, 2n, or 200n for that matter, is still O(n)
    $endgroup$
    – TemporalWolf
    Mar 4 at 18:09














14












14








14


3



$begingroup$


This code is to solve the Hacker Rank problem array left rotation.



A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].



Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers.



public static int rotLeft(int a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = 0;
temp = a[0];
for (int intK = 0; intK < a.Length; intK++)
{
a[a.Length - (a.Length - intK)] = a.Length - 1 == intK ? temp : a[a.Length - (a.Length - (intK + 1))];
}
}
return a;
}
static void Main(string args)
{
string nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
int result = rotLeft(a, d);
Console.WriteLine(string.Join(" ", result));
}


This program works fine, but it takes too long with some examples. How can I improve it?










share|improve this question











$endgroup$




This code is to solve the Hacker Rank problem array left rotation.



A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].



Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers.



public static int rotLeft(int a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = 0;
temp = a[0];
for (int intK = 0; intK < a.Length; intK++)
{
a[a.Length - (a.Length - intK)] = a.Length - 1 == intK ? temp : a[a.Length - (a.Length - (intK + 1))];
}
}
return a;
}
static void Main(string args)
{
string nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
int result = rotLeft(a, d);
Console.WriteLine(string.Join(" ", result));
}


This program works fine, but it takes too long with some examples. How can I improve it?







c# algorithm programming-challenge time-limit-exceeded






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 4 at 8:52









Toby Speight

27k742119




27k742119










asked Mar 4 at 6:11









RamakrishnaRamakrishna

7316




7316








  • 6




    $begingroup$
    The best code is no code at all. Do you actually need to rotate the array, or just print the elements in rotated order? Because if that’s the case then you can save a whole lot of copying around.
    $endgroup$
    – Konrad Rudolph
    Mar 4 at 12:45










  • $begingroup$
    From O(n^2) to O(n): int n = d % a.Length; var b = a.Skip(n).Concat(a.Take(n)).ToArray();. You can always get rid of the lazy enumerable when its too slow.
    $endgroup$
    – Caramiriel
    Mar 4 at 13:26






  • 7




    $begingroup$
    @Caramiriel, you've got the wrong box. The one for answers is further down the page.
    $endgroup$
    – Peter Taylor
    Mar 4 at 14:32






  • 1




    $begingroup$
    @Caramiriel this isn't O(n) because Skip is not clever... as far as I know it iterates the collection to skip the items.
    $endgroup$
    – t3chb0t
    Mar 4 at 16:00






  • 4




    $begingroup$
    @t3chb0t Even if it goes through the array twice, 2n, or 200n for that matter, is still O(n)
    $endgroup$
    – TemporalWolf
    Mar 4 at 18:09














  • 6




    $begingroup$
    The best code is no code at all. Do you actually need to rotate the array, or just print the elements in rotated order? Because if that’s the case then you can save a whole lot of copying around.
    $endgroup$
    – Konrad Rudolph
    Mar 4 at 12:45










  • $begingroup$
    From O(n^2) to O(n): int n = d % a.Length; var b = a.Skip(n).Concat(a.Take(n)).ToArray();. You can always get rid of the lazy enumerable when its too slow.
    $endgroup$
    – Caramiriel
    Mar 4 at 13:26






  • 7




    $begingroup$
    @Caramiriel, you've got the wrong box. The one for answers is further down the page.
    $endgroup$
    – Peter Taylor
    Mar 4 at 14:32






  • 1




    $begingroup$
    @Caramiriel this isn't O(n) because Skip is not clever... as far as I know it iterates the collection to skip the items.
    $endgroup$
    – t3chb0t
    Mar 4 at 16:00






  • 4




    $begingroup$
    @t3chb0t Even if it goes through the array twice, 2n, or 200n for that matter, is still O(n)
    $endgroup$
    – TemporalWolf
    Mar 4 at 18:09








6




6




$begingroup$
The best code is no code at all. Do you actually need to rotate the array, or just print the elements in rotated order? Because if that’s the case then you can save a whole lot of copying around.
$endgroup$
– Konrad Rudolph
Mar 4 at 12:45




$begingroup$
The best code is no code at all. Do you actually need to rotate the array, or just print the elements in rotated order? Because if that’s the case then you can save a whole lot of copying around.
$endgroup$
– Konrad Rudolph
Mar 4 at 12:45












$begingroup$
From O(n^2) to O(n): int n = d % a.Length; var b = a.Skip(n).Concat(a.Take(n)).ToArray();. You can always get rid of the lazy enumerable when its too slow.
$endgroup$
– Caramiriel
Mar 4 at 13:26




$begingroup$
From O(n^2) to O(n): int n = d % a.Length; var b = a.Skip(n).Concat(a.Take(n)).ToArray();. You can always get rid of the lazy enumerable when its too slow.
$endgroup$
– Caramiriel
Mar 4 at 13:26




7




7




$begingroup$
@Caramiriel, you've got the wrong box. The one for answers is further down the page.
$endgroup$
– Peter Taylor
Mar 4 at 14:32




$begingroup$
@Caramiriel, you've got the wrong box. The one for answers is further down the page.
$endgroup$
– Peter Taylor
Mar 4 at 14:32




1




1




$begingroup$
@Caramiriel this isn't O(n) because Skip is not clever... as far as I know it iterates the collection to skip the items.
$endgroup$
– t3chb0t
Mar 4 at 16:00




$begingroup$
@Caramiriel this isn't O(n) because Skip is not clever... as far as I know it iterates the collection to skip the items.
$endgroup$
– t3chb0t
Mar 4 at 16:00




4




4




$begingroup$
@t3chb0t Even if it goes through the array twice, 2n, or 200n for that matter, is still O(n)
$endgroup$
– TemporalWolf
Mar 4 at 18:09




$begingroup$
@t3chb0t Even if it goes through the array twice, 2n, or 200n for that matter, is still O(n)
$endgroup$
– TemporalWolf
Mar 4 at 18:09










5 Answers
5






active

oldest

votes


















17












$begingroup$

About naming:



intI and intK: don't include the type in the variable name, it is obvious from the context and intellisense and as a loop index a plain i and k are more understandable.





A first simple optimization is that you can avoid the check if intK has reached the end:




a.Length - 1 == intK ?




Instead you can just iterate up to a.Length - 1 and then append temp at the end:



public static int rotLeft(int a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = a[0];

for (int intK = 0; intK < a.Length - 1; intK++)
{
a[a.Length - (a.Length - intK)] = a[a.Length - (a.Length - (intK + 1))];
}

a[a.Length - 1] = temp;
}

return a;
}




Next step is to consider the math:



a.Length - (a.Length - intK) = a.Length - a.Length + intK = intK


and in the same way:



a.Length - (a.Length - (intK + 1)) = intK + 1


So you could write:



public static int rotLeft(int a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = a[0];

for (int intK = 0; intK < a.Length - 1; intK++)
{
a[intK] = a[intK + 1];
}

a[a.Length - 1] = temp;
}

return a;
}




But the real performance problem is that you move each entry in the array d number of times. You can move each entry just once by moving it d places. A simple way to do that could be:



public static int rotLeft(int a, int d)
{
int temp = new int[d];

for (int i = 0; i < d; i++)
temp[i] = a[i];

for (int i = d; i < a.Length; i++)
{
a[i - d] = a[i];
}

for (int i = 0; i < d; i++)
a[a.Length - d + i] = temp[i];

return a;
}




Another issue is that you operate on the input array a directly and return it as a return value. In this way both the return value and a contains the shifted values. In a challenge like this it may not be important, but I think I would return a new array with the shifted data leaving a unchanged - in "real world":



public static int rotLeft(int a, int d)
{
int result = new int[a.Length];

for (int i = d; i < a.Length; i++)
{
result[i - d] = a[i];
}

for (int j = 0; j < d; j++)
{
result[a.Length - d + j] = a[j];
}

return result;
}


If you want to operate on a directly intentionally it would be more consistent returning void to signal that you're operating on the input directly.






share|improve this answer











$endgroup$





















    16












    $begingroup$

    I guess your code is slow because of the two loops and its O(n^2) complexity. You can actually solve it with only one loop by rotating the index with % (modulo). This would even allow you to rotate the array in both directions;



    public static IEnumerable<T> Shift<T>(this T source, int count)
    {
    for (int i = 0; i < source.Length; i++)
    {
    var j =
    count > 0
    ? (i + count) % source.Length
    : (i + count + source.Length) % source.Length;
    yield return source[j];
    }
    }





    share|improve this answer









    $endgroup$









    • 11




      $begingroup$
      In fact, a general tip for programming challenges like this is that, whenever the challenge says "repeat this operation N times," it almost always actually means "find a faster way to get the same result as if you'd repeated the operation N times." That's because the challenges are meant to be challenging, and just writing a for loop to run the same code multiple times is really no challenge at all.
      $endgroup$
      – Ilmari Karonen
      Mar 4 at 10:00












    • $begingroup$
      % is typically slow; and i+count can't wrap more than once. So really you just need a conditional subtract. If you're actually copying the array, hopefully the compiler can split it into two loops that simply copy the 1st / 2nd parts of the array without doing a bunch of expensive per-index calculation, like Henrik's answer. Also hopefully the compiler will hoist the count>0 check out of the loop.
      $endgroup$
      – Peter Cordes
      Mar 4 at 10:02








    • 8




      $begingroup$
      @PeterCordes - I think % is clearer and never so slow as to justify such an optimization without profiling first. I would be very surprised if it were the bottleneck in application software, rather than, say, disk IO.
      $endgroup$
      – Alex Reinking
      Mar 4 at 10:41










    • $begingroup$
      In C, a simplistic microbenchmark doing just a modulo increment shows that it's about 6x slower on a Haswell CPU. is it better to avoid using the mod operator when possible?. Most things aren't a big deal, but integer division is slow unless it's by a compile-time constant that the compiler can turn into a multiply+shift. The OP already said that their solution for rotating an array was too slow rotating 1 element at a time, so presumably a factor of 6 (or more if the compiler can turn it into 2x memcpy) could matter.
      $endgroup$
      – Peter Cordes
      Mar 4 at 22:05






    • 3




      $begingroup$
      You can hoist the count > 0 check out of the loop by calculating the left-rotate count once. if(count < 0) count += source.Length; Then the loop becomes much more readable, and probably more efficient unless the compiler already managed to do that for you.
      $endgroup$
      – Peter Cordes
      Mar 4 at 22:14





















    8












    $begingroup$


        static void Main(string args)
    {
    string nd = Console.ReadLine().Split(' ');
    int n = Convert.ToInt32(nd[0]);
    int d = Convert.ToInt32(nd[1]);
    int a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));



    Don't Repeat Yourself. There's an easy opportunity here to factor out a method which reads an array of integers from stdin.



    In general I would prefer to remove the explicit lambda, but I think that in this case just passing Convert.ToInt32 would be ambiguous because of the overloads.






            int result = rotLeft(a, d);
    Console.WriteLine(string.Join(" ", result));
    }



    When implementing a spec, ask yourself what the inputs and the outputs are. As long as you respect those, you should be at liberty to optimise the processing. So it's not actually necessary to rotate the array: just to print the result of rotating it.



            Console.Write(a[d]);
    for (int i = d+1; i < a.Length; i++)
    {
    Console.Write(' ');
    Console.Write(a[i]);
    }
    for (int i = 0; i < d; i++)
    {
    Console.Write(' ');
    Console.Write(a[i]);
    }




    But I think that that code probably has a bug. Does the spec make any guarantees about the value of d other than that it's an integer? Can it be negative? Can it be greater than n?






    share|improve this answer









    $endgroup$













    • $begingroup$
      Most of the I/O code is provided as part of the challenge. The only thing OP has to provide is the code inside the rotLeft function, which should return the rotated array.
      $endgroup$
      – jcaron
      Mar 4 at 11:50










    • $begingroup$
      @jcaron, it's OP's responsibility to ask only about their own code. The help centre is quite explicit that any aspect of the code posted is fair game for feedback and criticism.
      $endgroup$
      – Peter Taylor
      Mar 4 at 13:01










    • $begingroup$
      The constraints say that 1 <= d <= n, so yes, we have guarantees about d.
      $endgroup$
      – Astrinus
      Mar 5 at 8:12






    • 1




      $begingroup$
      @Astrinus, if I wanted answers to those questions I'd have posted them as comments on the question. As I see it, one of the things a code review should do is challenge OP to think about whether they've fully understood the spec, and whether they can update the code if the spec (or their understanding of it) changes.
      $endgroup$
      – Peter Taylor
      Mar 5 at 8:30



















    3












    $begingroup$

    You are focusing on the wrong portion of the problem. You're thinking the array needs to be rotated. The output of the array needs to be "rotated" but the array can remain as-is.



    So simply write a loop that starts at the middle of the array, incrementing until it hits the end, and then continues along from the beginning until it hits the index just before the one you started at.



    The output of that loop is the "rotated" array, from the visibility of the testing framework.



        string sep = "";
    for (int i = d % a.Length; i < a.Length; i++) {
    Console.Write(sep);
    Console.Write(a[i]);
    sep = " ";
    }
    for (int i = 0; i < d % a.Length; i++)
    {
    Console.Write(sep);
    Console.Write(a[i]);
    sep = " ";
    }


    This is a great reason why you should sometimes see hackerrank as a poor place to really learn programming.



    hackerrank primarily contains programming problems harvested from programming competitions. Competitions where these problems are meant to be solved fast, with a time deadline. This means that the problems are more about building a quick, clever, solution and less about really learning the lessons that would help you in a programming career.



    Another example of a solution is



        string sep = "";
    for (int i = d; a.Length + d - i > 0; i++) {
    Console.Write(sep);
    Console.Write(a[i % a.Length]);
    sep = " ";
    }


    Which is, according to hackerranks estimation, "just as good" as the above solution, but is far less readable.






    share|improve this answer











    $endgroup$









    • 1




      $begingroup$
      Well one thing one should certainly learn from this challenge is what string.Join does and how it avoids the rather awful for loop :) (The given solution also misses some necessary modulo ops)
      $endgroup$
      – Voo
      Mar 4 at 19:21












    • $begingroup$
      @Voo Out of curiosity, which modulo does this miss? I know I wrote it by hand without the aid of a computer, but the loop (in my 5 element example, starting at index 3 would be 3, 4, 5, 6, 7 (8 would be 5 + 3 - 8, so it wouldn't get there). and 3 % 5 = 3, 4 % 5 = 4, 5 % 5 = 0, 6 % 5 = 1, 7 % 5 = 2. Now, I just might have a bug in there after all; but, maybe not, which is a perfect example of why writing it this way is less than ideal and why hackerranks fascination with programming competitions as question banks is bad.
      $endgroup$
      – Edwin Buck
      Mar 4 at 20:20






    • 2




      $begingroup$
      You're supposed to do n rotations. Nowhere does it say that n < arr.Length. You could have an array of 1,2,3 and d=5. Both of your solutions fail with an out of bounds there.
      $endgroup$
      – Voo
      Mar 4 at 21:14






    • 1




      $begingroup$
      @Voo: if you read the challenge, you see that 1 <= d <= n, i.e. rotate an n elements array by d steps, so you cannot have more rotations than elements.
      $endgroup$
      – Astrinus
      Mar 5 at 8:15










    • $begingroup$
      @Voo I think you keep focusing on how (in my latter example) i is often out-of-range of the array. That's probably why you keep saying "out of bounds" which would cause an error if I was pulling out the i element of the array. But I'm not pulling i out of the array, I'm pulling i % a.Length which can't be out of bounds.
      $endgroup$
      – Edwin Buck
      Mar 5 at 17:10



















    1












    $begingroup$



    • Because of the 2 imbricated for loops in the original code,



      for (int intI = 0; intI < d; intI++) {

      for (int intK = 0; intK < a.Length; intK++) {
      ...
      }
      }




    your code performs d * a.Length actions. Which takes quadratic time when d is near a.Length/2.



    So, we may ask, can we do better ?





    • The answer is yes. There is a linear-time solution. It is as follows :




      1. "mirror" the first d elements

      2. mirror the whole array

      3. mirror the size-d first elements.




    Implementation of mirror (rever an array) is left to the reader.



    Linear time complexity. 0(1) extra room needed (loop variable and temporary for exchange).



    So it is clearly an improvement on the original version.






    share|improve this answer











    $endgroup$













    • $begingroup$
      You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
      $endgroup$
      – Toby Speight
      Mar 5 at 11:02












    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214680%2fhacker-rank-array-left-rotation%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    5 Answers
    5






    active

    oldest

    votes








    5 Answers
    5






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    17












    $begingroup$

    About naming:



    intI and intK: don't include the type in the variable name, it is obvious from the context and intellisense and as a loop index a plain i and k are more understandable.





    A first simple optimization is that you can avoid the check if intK has reached the end:




    a.Length - 1 == intK ?




    Instead you can just iterate up to a.Length - 1 and then append temp at the end:



    public static int rotLeft(int a, int d)
    {
    for (int intI = 0; intI < d; intI++)
    {
    int temp = a[0];

    for (int intK = 0; intK < a.Length - 1; intK++)
    {
    a[a.Length - (a.Length - intK)] = a[a.Length - (a.Length - (intK + 1))];
    }

    a[a.Length - 1] = temp;
    }

    return a;
    }




    Next step is to consider the math:



    a.Length - (a.Length - intK) = a.Length - a.Length + intK = intK


    and in the same way:



    a.Length - (a.Length - (intK + 1)) = intK + 1


    So you could write:



    public static int rotLeft(int a, int d)
    {
    for (int intI = 0; intI < d; intI++)
    {
    int temp = a[0];

    for (int intK = 0; intK < a.Length - 1; intK++)
    {
    a[intK] = a[intK + 1];
    }

    a[a.Length - 1] = temp;
    }

    return a;
    }




    But the real performance problem is that you move each entry in the array d number of times. You can move each entry just once by moving it d places. A simple way to do that could be:



    public static int rotLeft(int a, int d)
    {
    int temp = new int[d];

    for (int i = 0; i < d; i++)
    temp[i] = a[i];

    for (int i = d; i < a.Length; i++)
    {
    a[i - d] = a[i];
    }

    for (int i = 0; i < d; i++)
    a[a.Length - d + i] = temp[i];

    return a;
    }




    Another issue is that you operate on the input array a directly and return it as a return value. In this way both the return value and a contains the shifted values. In a challenge like this it may not be important, but I think I would return a new array with the shifted data leaving a unchanged - in "real world":



    public static int rotLeft(int a, int d)
    {
    int result = new int[a.Length];

    for (int i = d; i < a.Length; i++)
    {
    result[i - d] = a[i];
    }

    for (int j = 0; j < d; j++)
    {
    result[a.Length - d + j] = a[j];
    }

    return result;
    }


    If you want to operate on a directly intentionally it would be more consistent returning void to signal that you're operating on the input directly.






    share|improve this answer











    $endgroup$


















      17












      $begingroup$

      About naming:



      intI and intK: don't include the type in the variable name, it is obvious from the context and intellisense and as a loop index a plain i and k are more understandable.





      A first simple optimization is that you can avoid the check if intK has reached the end:




      a.Length - 1 == intK ?




      Instead you can just iterate up to a.Length - 1 and then append temp at the end:



      public static int rotLeft(int a, int d)
      {
      for (int intI = 0; intI < d; intI++)
      {
      int temp = a[0];

      for (int intK = 0; intK < a.Length - 1; intK++)
      {
      a[a.Length - (a.Length - intK)] = a[a.Length - (a.Length - (intK + 1))];
      }

      a[a.Length - 1] = temp;
      }

      return a;
      }




      Next step is to consider the math:



      a.Length - (a.Length - intK) = a.Length - a.Length + intK = intK


      and in the same way:



      a.Length - (a.Length - (intK + 1)) = intK + 1


      So you could write:



      public static int rotLeft(int a, int d)
      {
      for (int intI = 0; intI < d; intI++)
      {
      int temp = a[0];

      for (int intK = 0; intK < a.Length - 1; intK++)
      {
      a[intK] = a[intK + 1];
      }

      a[a.Length - 1] = temp;
      }

      return a;
      }




      But the real performance problem is that you move each entry in the array d number of times. You can move each entry just once by moving it d places. A simple way to do that could be:



      public static int rotLeft(int a, int d)
      {
      int temp = new int[d];

      for (int i = 0; i < d; i++)
      temp[i] = a[i];

      for (int i = d; i < a.Length; i++)
      {
      a[i - d] = a[i];
      }

      for (int i = 0; i < d; i++)
      a[a.Length - d + i] = temp[i];

      return a;
      }




      Another issue is that you operate on the input array a directly and return it as a return value. In this way both the return value and a contains the shifted values. In a challenge like this it may not be important, but I think I would return a new array with the shifted data leaving a unchanged - in "real world":



      public static int rotLeft(int a, int d)
      {
      int result = new int[a.Length];

      for (int i = d; i < a.Length; i++)
      {
      result[i - d] = a[i];
      }

      for (int j = 0; j < d; j++)
      {
      result[a.Length - d + j] = a[j];
      }

      return result;
      }


      If you want to operate on a directly intentionally it would be more consistent returning void to signal that you're operating on the input directly.






      share|improve this answer











      $endgroup$
















        17












        17








        17





        $begingroup$

        About naming:



        intI and intK: don't include the type in the variable name, it is obvious from the context and intellisense and as a loop index a plain i and k are more understandable.





        A first simple optimization is that you can avoid the check if intK has reached the end:




        a.Length - 1 == intK ?




        Instead you can just iterate up to a.Length - 1 and then append temp at the end:



        public static int rotLeft(int a, int d)
        {
        for (int intI = 0; intI < d; intI++)
        {
        int temp = a[0];

        for (int intK = 0; intK < a.Length - 1; intK++)
        {
        a[a.Length - (a.Length - intK)] = a[a.Length - (a.Length - (intK + 1))];
        }

        a[a.Length - 1] = temp;
        }

        return a;
        }




        Next step is to consider the math:



        a.Length - (a.Length - intK) = a.Length - a.Length + intK = intK


        and in the same way:



        a.Length - (a.Length - (intK + 1)) = intK + 1


        So you could write:



        public static int rotLeft(int a, int d)
        {
        for (int intI = 0; intI < d; intI++)
        {
        int temp = a[0];

        for (int intK = 0; intK < a.Length - 1; intK++)
        {
        a[intK] = a[intK + 1];
        }

        a[a.Length - 1] = temp;
        }

        return a;
        }




        But the real performance problem is that you move each entry in the array d number of times. You can move each entry just once by moving it d places. A simple way to do that could be:



        public static int rotLeft(int a, int d)
        {
        int temp = new int[d];

        for (int i = 0; i < d; i++)
        temp[i] = a[i];

        for (int i = d; i < a.Length; i++)
        {
        a[i - d] = a[i];
        }

        for (int i = 0; i < d; i++)
        a[a.Length - d + i] = temp[i];

        return a;
        }




        Another issue is that you operate on the input array a directly and return it as a return value. In this way both the return value and a contains the shifted values. In a challenge like this it may not be important, but I think I would return a new array with the shifted data leaving a unchanged - in "real world":



        public static int rotLeft(int a, int d)
        {
        int result = new int[a.Length];

        for (int i = d; i < a.Length; i++)
        {
        result[i - d] = a[i];
        }

        for (int j = 0; j < d; j++)
        {
        result[a.Length - d + j] = a[j];
        }

        return result;
        }


        If you want to operate on a directly intentionally it would be more consistent returning void to signal that you're operating on the input directly.






        share|improve this answer











        $endgroup$



        About naming:



        intI and intK: don't include the type in the variable name, it is obvious from the context and intellisense and as a loop index a plain i and k are more understandable.





        A first simple optimization is that you can avoid the check if intK has reached the end:




        a.Length - 1 == intK ?




        Instead you can just iterate up to a.Length - 1 and then append temp at the end:



        public static int rotLeft(int a, int d)
        {
        for (int intI = 0; intI < d; intI++)
        {
        int temp = a[0];

        for (int intK = 0; intK < a.Length - 1; intK++)
        {
        a[a.Length - (a.Length - intK)] = a[a.Length - (a.Length - (intK + 1))];
        }

        a[a.Length - 1] = temp;
        }

        return a;
        }




        Next step is to consider the math:



        a.Length - (a.Length - intK) = a.Length - a.Length + intK = intK


        and in the same way:



        a.Length - (a.Length - (intK + 1)) = intK + 1


        So you could write:



        public static int rotLeft(int a, int d)
        {
        for (int intI = 0; intI < d; intI++)
        {
        int temp = a[0];

        for (int intK = 0; intK < a.Length - 1; intK++)
        {
        a[intK] = a[intK + 1];
        }

        a[a.Length - 1] = temp;
        }

        return a;
        }




        But the real performance problem is that you move each entry in the array d number of times. You can move each entry just once by moving it d places. A simple way to do that could be:



        public static int rotLeft(int a, int d)
        {
        int temp = new int[d];

        for (int i = 0; i < d; i++)
        temp[i] = a[i];

        for (int i = d; i < a.Length; i++)
        {
        a[i - d] = a[i];
        }

        for (int i = 0; i < d; i++)
        a[a.Length - d + i] = temp[i];

        return a;
        }




        Another issue is that you operate on the input array a directly and return it as a return value. In this way both the return value and a contains the shifted values. In a challenge like this it may not be important, but I think I would return a new array with the shifted data leaving a unchanged - in "real world":



        public static int rotLeft(int a, int d)
        {
        int result = new int[a.Length];

        for (int i = d; i < a.Length; i++)
        {
        result[i - d] = a[i];
        }

        for (int j = 0; j < d; j++)
        {
        result[a.Length - d + j] = a[j];
        }

        return result;
        }


        If you want to operate on a directly intentionally it would be more consistent returning void to signal that you're operating on the input directly.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 4 at 8:28

























        answered Mar 4 at 8:03









        Henrik HansenHenrik Hansen

        8,29011231




        8,29011231

























            16












            $begingroup$

            I guess your code is slow because of the two loops and its O(n^2) complexity. You can actually solve it with only one loop by rotating the index with % (modulo). This would even allow you to rotate the array in both directions;



            public static IEnumerable<T> Shift<T>(this T source, int count)
            {
            for (int i = 0; i < source.Length; i++)
            {
            var j =
            count > 0
            ? (i + count) % source.Length
            : (i + count + source.Length) % source.Length;
            yield return source[j];
            }
            }





            share|improve this answer









            $endgroup$









            • 11




              $begingroup$
              In fact, a general tip for programming challenges like this is that, whenever the challenge says "repeat this operation N times," it almost always actually means "find a faster way to get the same result as if you'd repeated the operation N times." That's because the challenges are meant to be challenging, and just writing a for loop to run the same code multiple times is really no challenge at all.
              $endgroup$
              – Ilmari Karonen
              Mar 4 at 10:00












            • $begingroup$
              % is typically slow; and i+count can't wrap more than once. So really you just need a conditional subtract. If you're actually copying the array, hopefully the compiler can split it into two loops that simply copy the 1st / 2nd parts of the array without doing a bunch of expensive per-index calculation, like Henrik's answer. Also hopefully the compiler will hoist the count>0 check out of the loop.
              $endgroup$
              – Peter Cordes
              Mar 4 at 10:02








            • 8




              $begingroup$
              @PeterCordes - I think % is clearer and never so slow as to justify such an optimization without profiling first. I would be very surprised if it were the bottleneck in application software, rather than, say, disk IO.
              $endgroup$
              – Alex Reinking
              Mar 4 at 10:41










            • $begingroup$
              In C, a simplistic microbenchmark doing just a modulo increment shows that it's about 6x slower on a Haswell CPU. is it better to avoid using the mod operator when possible?. Most things aren't a big deal, but integer division is slow unless it's by a compile-time constant that the compiler can turn into a multiply+shift. The OP already said that their solution for rotating an array was too slow rotating 1 element at a time, so presumably a factor of 6 (or more if the compiler can turn it into 2x memcpy) could matter.
              $endgroup$
              – Peter Cordes
              Mar 4 at 22:05






            • 3




              $begingroup$
              You can hoist the count > 0 check out of the loop by calculating the left-rotate count once. if(count < 0) count += source.Length; Then the loop becomes much more readable, and probably more efficient unless the compiler already managed to do that for you.
              $endgroup$
              – Peter Cordes
              Mar 4 at 22:14


















            16












            $begingroup$

            I guess your code is slow because of the two loops and its O(n^2) complexity. You can actually solve it with only one loop by rotating the index with % (modulo). This would even allow you to rotate the array in both directions;



            public static IEnumerable<T> Shift<T>(this T source, int count)
            {
            for (int i = 0; i < source.Length; i++)
            {
            var j =
            count > 0
            ? (i + count) % source.Length
            : (i + count + source.Length) % source.Length;
            yield return source[j];
            }
            }





            share|improve this answer









            $endgroup$









            • 11




              $begingroup$
              In fact, a general tip for programming challenges like this is that, whenever the challenge says "repeat this operation N times," it almost always actually means "find a faster way to get the same result as if you'd repeated the operation N times." That's because the challenges are meant to be challenging, and just writing a for loop to run the same code multiple times is really no challenge at all.
              $endgroup$
              – Ilmari Karonen
              Mar 4 at 10:00












            • $begingroup$
              % is typically slow; and i+count can't wrap more than once. So really you just need a conditional subtract. If you're actually copying the array, hopefully the compiler can split it into two loops that simply copy the 1st / 2nd parts of the array without doing a bunch of expensive per-index calculation, like Henrik's answer. Also hopefully the compiler will hoist the count>0 check out of the loop.
              $endgroup$
              – Peter Cordes
              Mar 4 at 10:02








            • 8




              $begingroup$
              @PeterCordes - I think % is clearer and never so slow as to justify such an optimization without profiling first. I would be very surprised if it were the bottleneck in application software, rather than, say, disk IO.
              $endgroup$
              – Alex Reinking
              Mar 4 at 10:41










            • $begingroup$
              In C, a simplistic microbenchmark doing just a modulo increment shows that it's about 6x slower on a Haswell CPU. is it better to avoid using the mod operator when possible?. Most things aren't a big deal, but integer division is slow unless it's by a compile-time constant that the compiler can turn into a multiply+shift. The OP already said that their solution for rotating an array was too slow rotating 1 element at a time, so presumably a factor of 6 (or more if the compiler can turn it into 2x memcpy) could matter.
              $endgroup$
              – Peter Cordes
              Mar 4 at 22:05






            • 3




              $begingroup$
              You can hoist the count > 0 check out of the loop by calculating the left-rotate count once. if(count < 0) count += source.Length; Then the loop becomes much more readable, and probably more efficient unless the compiler already managed to do that for you.
              $endgroup$
              – Peter Cordes
              Mar 4 at 22:14
















            16












            16








            16





            $begingroup$

            I guess your code is slow because of the two loops and its O(n^2) complexity. You can actually solve it with only one loop by rotating the index with % (modulo). This would even allow you to rotate the array in both directions;



            public static IEnumerable<T> Shift<T>(this T source, int count)
            {
            for (int i = 0; i < source.Length; i++)
            {
            var j =
            count > 0
            ? (i + count) % source.Length
            : (i + count + source.Length) % source.Length;
            yield return source[j];
            }
            }





            share|improve this answer









            $endgroup$



            I guess your code is slow because of the two loops and its O(n^2) complexity. You can actually solve it with only one loop by rotating the index with % (modulo). This would even allow you to rotate the array in both directions;



            public static IEnumerable<T> Shift<T>(this T source, int count)
            {
            for (int i = 0; i < source.Length; i++)
            {
            var j =
            count > 0
            ? (i + count) % source.Length
            : (i + count + source.Length) % source.Length;
            yield return source[j];
            }
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 4 at 8:44









            t3chb0tt3chb0t

            35.1k754125




            35.1k754125








            • 11




              $begingroup$
              In fact, a general tip for programming challenges like this is that, whenever the challenge says "repeat this operation N times," it almost always actually means "find a faster way to get the same result as if you'd repeated the operation N times." That's because the challenges are meant to be challenging, and just writing a for loop to run the same code multiple times is really no challenge at all.
              $endgroup$
              – Ilmari Karonen
              Mar 4 at 10:00












            • $begingroup$
              % is typically slow; and i+count can't wrap more than once. So really you just need a conditional subtract. If you're actually copying the array, hopefully the compiler can split it into two loops that simply copy the 1st / 2nd parts of the array without doing a bunch of expensive per-index calculation, like Henrik's answer. Also hopefully the compiler will hoist the count>0 check out of the loop.
              $endgroup$
              – Peter Cordes
              Mar 4 at 10:02








            • 8




              $begingroup$
              @PeterCordes - I think % is clearer and never so slow as to justify such an optimization without profiling first. I would be very surprised if it were the bottleneck in application software, rather than, say, disk IO.
              $endgroup$
              – Alex Reinking
              Mar 4 at 10:41










            • $begingroup$
              In C, a simplistic microbenchmark doing just a modulo increment shows that it's about 6x slower on a Haswell CPU. is it better to avoid using the mod operator when possible?. Most things aren't a big deal, but integer division is slow unless it's by a compile-time constant that the compiler can turn into a multiply+shift. The OP already said that their solution for rotating an array was too slow rotating 1 element at a time, so presumably a factor of 6 (or more if the compiler can turn it into 2x memcpy) could matter.
              $endgroup$
              – Peter Cordes
              Mar 4 at 22:05






            • 3




              $begingroup$
              You can hoist the count > 0 check out of the loop by calculating the left-rotate count once. if(count < 0) count += source.Length; Then the loop becomes much more readable, and probably more efficient unless the compiler already managed to do that for you.
              $endgroup$
              – Peter Cordes
              Mar 4 at 22:14
















            • 11




              $begingroup$
              In fact, a general tip for programming challenges like this is that, whenever the challenge says "repeat this operation N times," it almost always actually means "find a faster way to get the same result as if you'd repeated the operation N times." That's because the challenges are meant to be challenging, and just writing a for loop to run the same code multiple times is really no challenge at all.
              $endgroup$
              – Ilmari Karonen
              Mar 4 at 10:00












            • $begingroup$
              % is typically slow; and i+count can't wrap more than once. So really you just need a conditional subtract. If you're actually copying the array, hopefully the compiler can split it into two loops that simply copy the 1st / 2nd parts of the array without doing a bunch of expensive per-index calculation, like Henrik's answer. Also hopefully the compiler will hoist the count>0 check out of the loop.
              $endgroup$
              – Peter Cordes
              Mar 4 at 10:02








            • 8




              $begingroup$
              @PeterCordes - I think % is clearer and never so slow as to justify such an optimization without profiling first. I would be very surprised if it were the bottleneck in application software, rather than, say, disk IO.
              $endgroup$
              – Alex Reinking
              Mar 4 at 10:41










            • $begingroup$
              In C, a simplistic microbenchmark doing just a modulo increment shows that it's about 6x slower on a Haswell CPU. is it better to avoid using the mod operator when possible?. Most things aren't a big deal, but integer division is slow unless it's by a compile-time constant that the compiler can turn into a multiply+shift. The OP already said that their solution for rotating an array was too slow rotating 1 element at a time, so presumably a factor of 6 (or more if the compiler can turn it into 2x memcpy) could matter.
              $endgroup$
              – Peter Cordes
              Mar 4 at 22:05






            • 3




              $begingroup$
              You can hoist the count > 0 check out of the loop by calculating the left-rotate count once. if(count < 0) count += source.Length; Then the loop becomes much more readable, and probably more efficient unless the compiler already managed to do that for you.
              $endgroup$
              – Peter Cordes
              Mar 4 at 22:14










            11




            11




            $begingroup$
            In fact, a general tip for programming challenges like this is that, whenever the challenge says "repeat this operation N times," it almost always actually means "find a faster way to get the same result as if you'd repeated the operation N times." That's because the challenges are meant to be challenging, and just writing a for loop to run the same code multiple times is really no challenge at all.
            $endgroup$
            – Ilmari Karonen
            Mar 4 at 10:00






            $begingroup$
            In fact, a general tip for programming challenges like this is that, whenever the challenge says "repeat this operation N times," it almost always actually means "find a faster way to get the same result as if you'd repeated the operation N times." That's because the challenges are meant to be challenging, and just writing a for loop to run the same code multiple times is really no challenge at all.
            $endgroup$
            – Ilmari Karonen
            Mar 4 at 10:00














            $begingroup$
            % is typically slow; and i+count can't wrap more than once. So really you just need a conditional subtract. If you're actually copying the array, hopefully the compiler can split it into two loops that simply copy the 1st / 2nd parts of the array without doing a bunch of expensive per-index calculation, like Henrik's answer. Also hopefully the compiler will hoist the count>0 check out of the loop.
            $endgroup$
            – Peter Cordes
            Mar 4 at 10:02






            $begingroup$
            % is typically slow; and i+count can't wrap more than once. So really you just need a conditional subtract. If you're actually copying the array, hopefully the compiler can split it into two loops that simply copy the 1st / 2nd parts of the array without doing a bunch of expensive per-index calculation, like Henrik's answer. Also hopefully the compiler will hoist the count>0 check out of the loop.
            $endgroup$
            – Peter Cordes
            Mar 4 at 10:02






            8




            8




            $begingroup$
            @PeterCordes - I think % is clearer and never so slow as to justify such an optimization without profiling first. I would be very surprised if it were the bottleneck in application software, rather than, say, disk IO.
            $endgroup$
            – Alex Reinking
            Mar 4 at 10:41




            $begingroup$
            @PeterCordes - I think % is clearer and never so slow as to justify such an optimization without profiling first. I would be very surprised if it were the bottleneck in application software, rather than, say, disk IO.
            $endgroup$
            – Alex Reinking
            Mar 4 at 10:41












            $begingroup$
            In C, a simplistic microbenchmark doing just a modulo increment shows that it's about 6x slower on a Haswell CPU. is it better to avoid using the mod operator when possible?. Most things aren't a big deal, but integer division is slow unless it's by a compile-time constant that the compiler can turn into a multiply+shift. The OP already said that their solution for rotating an array was too slow rotating 1 element at a time, so presumably a factor of 6 (or more if the compiler can turn it into 2x memcpy) could matter.
            $endgroup$
            – Peter Cordes
            Mar 4 at 22:05




            $begingroup$
            In C, a simplistic microbenchmark doing just a modulo increment shows that it's about 6x slower on a Haswell CPU. is it better to avoid using the mod operator when possible?. Most things aren't a big deal, but integer division is slow unless it's by a compile-time constant that the compiler can turn into a multiply+shift. The OP already said that their solution for rotating an array was too slow rotating 1 element at a time, so presumably a factor of 6 (or more if the compiler can turn it into 2x memcpy) could matter.
            $endgroup$
            – Peter Cordes
            Mar 4 at 22:05




            3




            3




            $begingroup$
            You can hoist the count > 0 check out of the loop by calculating the left-rotate count once. if(count < 0) count += source.Length; Then the loop becomes much more readable, and probably more efficient unless the compiler already managed to do that for you.
            $endgroup$
            – Peter Cordes
            Mar 4 at 22:14






            $begingroup$
            You can hoist the count > 0 check out of the loop by calculating the left-rotate count once. if(count < 0) count += source.Length; Then the loop becomes much more readable, and probably more efficient unless the compiler already managed to do that for you.
            $endgroup$
            – Peter Cordes
            Mar 4 at 22:14













            8












            $begingroup$


                static void Main(string args)
            {
            string nd = Console.ReadLine().Split(' ');
            int n = Convert.ToInt32(nd[0]);
            int d = Convert.ToInt32(nd[1]);
            int a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));



            Don't Repeat Yourself. There's an easy opportunity here to factor out a method which reads an array of integers from stdin.



            In general I would prefer to remove the explicit lambda, but I think that in this case just passing Convert.ToInt32 would be ambiguous because of the overloads.






                    int result = rotLeft(a, d);
            Console.WriteLine(string.Join(" ", result));
            }



            When implementing a spec, ask yourself what the inputs and the outputs are. As long as you respect those, you should be at liberty to optimise the processing. So it's not actually necessary to rotate the array: just to print the result of rotating it.



                    Console.Write(a[d]);
            for (int i = d+1; i < a.Length; i++)
            {
            Console.Write(' ');
            Console.Write(a[i]);
            }
            for (int i = 0; i < d; i++)
            {
            Console.Write(' ');
            Console.Write(a[i]);
            }




            But I think that that code probably has a bug. Does the spec make any guarantees about the value of d other than that it's an integer? Can it be negative? Can it be greater than n?






            share|improve this answer









            $endgroup$













            • $begingroup$
              Most of the I/O code is provided as part of the challenge. The only thing OP has to provide is the code inside the rotLeft function, which should return the rotated array.
              $endgroup$
              – jcaron
              Mar 4 at 11:50










            • $begingroup$
              @jcaron, it's OP's responsibility to ask only about their own code. The help centre is quite explicit that any aspect of the code posted is fair game for feedback and criticism.
              $endgroup$
              – Peter Taylor
              Mar 4 at 13:01










            • $begingroup$
              The constraints say that 1 <= d <= n, so yes, we have guarantees about d.
              $endgroup$
              – Astrinus
              Mar 5 at 8:12






            • 1




              $begingroup$
              @Astrinus, if I wanted answers to those questions I'd have posted them as comments on the question. As I see it, one of the things a code review should do is challenge OP to think about whether they've fully understood the spec, and whether they can update the code if the spec (or their understanding of it) changes.
              $endgroup$
              – Peter Taylor
              Mar 5 at 8:30
















            8












            $begingroup$


                static void Main(string args)
            {
            string nd = Console.ReadLine().Split(' ');
            int n = Convert.ToInt32(nd[0]);
            int d = Convert.ToInt32(nd[1]);
            int a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));



            Don't Repeat Yourself. There's an easy opportunity here to factor out a method which reads an array of integers from stdin.



            In general I would prefer to remove the explicit lambda, but I think that in this case just passing Convert.ToInt32 would be ambiguous because of the overloads.






                    int result = rotLeft(a, d);
            Console.WriteLine(string.Join(" ", result));
            }



            When implementing a spec, ask yourself what the inputs and the outputs are. As long as you respect those, you should be at liberty to optimise the processing. So it's not actually necessary to rotate the array: just to print the result of rotating it.



                    Console.Write(a[d]);
            for (int i = d+1; i < a.Length; i++)
            {
            Console.Write(' ');
            Console.Write(a[i]);
            }
            for (int i = 0; i < d; i++)
            {
            Console.Write(' ');
            Console.Write(a[i]);
            }




            But I think that that code probably has a bug. Does the spec make any guarantees about the value of d other than that it's an integer? Can it be negative? Can it be greater than n?






            share|improve this answer









            $endgroup$













            • $begingroup$
              Most of the I/O code is provided as part of the challenge. The only thing OP has to provide is the code inside the rotLeft function, which should return the rotated array.
              $endgroup$
              – jcaron
              Mar 4 at 11:50










            • $begingroup$
              @jcaron, it's OP's responsibility to ask only about their own code. The help centre is quite explicit that any aspect of the code posted is fair game for feedback and criticism.
              $endgroup$
              – Peter Taylor
              Mar 4 at 13:01










            • $begingroup$
              The constraints say that 1 <= d <= n, so yes, we have guarantees about d.
              $endgroup$
              – Astrinus
              Mar 5 at 8:12






            • 1




              $begingroup$
              @Astrinus, if I wanted answers to those questions I'd have posted them as comments on the question. As I see it, one of the things a code review should do is challenge OP to think about whether they've fully understood the spec, and whether they can update the code if the spec (or their understanding of it) changes.
              $endgroup$
              – Peter Taylor
              Mar 5 at 8:30














            8












            8








            8





            $begingroup$


                static void Main(string args)
            {
            string nd = Console.ReadLine().Split(' ');
            int n = Convert.ToInt32(nd[0]);
            int d = Convert.ToInt32(nd[1]);
            int a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));



            Don't Repeat Yourself. There's an easy opportunity here to factor out a method which reads an array of integers from stdin.



            In general I would prefer to remove the explicit lambda, but I think that in this case just passing Convert.ToInt32 would be ambiguous because of the overloads.






                    int result = rotLeft(a, d);
            Console.WriteLine(string.Join(" ", result));
            }



            When implementing a spec, ask yourself what the inputs and the outputs are. As long as you respect those, you should be at liberty to optimise the processing. So it's not actually necessary to rotate the array: just to print the result of rotating it.



                    Console.Write(a[d]);
            for (int i = d+1; i < a.Length; i++)
            {
            Console.Write(' ');
            Console.Write(a[i]);
            }
            for (int i = 0; i < d; i++)
            {
            Console.Write(' ');
            Console.Write(a[i]);
            }




            But I think that that code probably has a bug. Does the spec make any guarantees about the value of d other than that it's an integer? Can it be negative? Can it be greater than n?






            share|improve this answer









            $endgroup$




                static void Main(string args)
            {
            string nd = Console.ReadLine().Split(' ');
            int n = Convert.ToInt32(nd[0]);
            int d = Convert.ToInt32(nd[1]);
            int a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));



            Don't Repeat Yourself. There's an easy opportunity here to factor out a method which reads an array of integers from stdin.



            In general I would prefer to remove the explicit lambda, but I think that in this case just passing Convert.ToInt32 would be ambiguous because of the overloads.






                    int result = rotLeft(a, d);
            Console.WriteLine(string.Join(" ", result));
            }



            When implementing a spec, ask yourself what the inputs and the outputs are. As long as you respect those, you should be at liberty to optimise the processing. So it's not actually necessary to rotate the array: just to print the result of rotating it.



                    Console.Write(a[d]);
            for (int i = d+1; i < a.Length; i++)
            {
            Console.Write(' ');
            Console.Write(a[i]);
            }
            for (int i = 0; i < d; i++)
            {
            Console.Write(' ');
            Console.Write(a[i]);
            }




            But I think that that code probably has a bug. Does the spec make any guarantees about the value of d other than that it's an integer? Can it be negative? Can it be greater than n?







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 4 at 8:43









            Peter TaylorPeter Taylor

            18.3k2964




            18.3k2964












            • $begingroup$
              Most of the I/O code is provided as part of the challenge. The only thing OP has to provide is the code inside the rotLeft function, which should return the rotated array.
              $endgroup$
              – jcaron
              Mar 4 at 11:50










            • $begingroup$
              @jcaron, it's OP's responsibility to ask only about their own code. The help centre is quite explicit that any aspect of the code posted is fair game for feedback and criticism.
              $endgroup$
              – Peter Taylor
              Mar 4 at 13:01










            • $begingroup$
              The constraints say that 1 <= d <= n, so yes, we have guarantees about d.
              $endgroup$
              – Astrinus
              Mar 5 at 8:12






            • 1




              $begingroup$
              @Astrinus, if I wanted answers to those questions I'd have posted them as comments on the question. As I see it, one of the things a code review should do is challenge OP to think about whether they've fully understood the spec, and whether they can update the code if the spec (or their understanding of it) changes.
              $endgroup$
              – Peter Taylor
              Mar 5 at 8:30


















            • $begingroup$
              Most of the I/O code is provided as part of the challenge. The only thing OP has to provide is the code inside the rotLeft function, which should return the rotated array.
              $endgroup$
              – jcaron
              Mar 4 at 11:50










            • $begingroup$
              @jcaron, it's OP's responsibility to ask only about their own code. The help centre is quite explicit that any aspect of the code posted is fair game for feedback and criticism.
              $endgroup$
              – Peter Taylor
              Mar 4 at 13:01










            • $begingroup$
              The constraints say that 1 <= d <= n, so yes, we have guarantees about d.
              $endgroup$
              – Astrinus
              Mar 5 at 8:12






            • 1




              $begingroup$
              @Astrinus, if I wanted answers to those questions I'd have posted them as comments on the question. As I see it, one of the things a code review should do is challenge OP to think about whether they've fully understood the spec, and whether they can update the code if the spec (or their understanding of it) changes.
              $endgroup$
              – Peter Taylor
              Mar 5 at 8:30
















            $begingroup$
            Most of the I/O code is provided as part of the challenge. The only thing OP has to provide is the code inside the rotLeft function, which should return the rotated array.
            $endgroup$
            – jcaron
            Mar 4 at 11:50




            $begingroup$
            Most of the I/O code is provided as part of the challenge. The only thing OP has to provide is the code inside the rotLeft function, which should return the rotated array.
            $endgroup$
            – jcaron
            Mar 4 at 11:50












            $begingroup$
            @jcaron, it's OP's responsibility to ask only about their own code. The help centre is quite explicit that any aspect of the code posted is fair game for feedback and criticism.
            $endgroup$
            – Peter Taylor
            Mar 4 at 13:01




            $begingroup$
            @jcaron, it's OP's responsibility to ask only about their own code. The help centre is quite explicit that any aspect of the code posted is fair game for feedback and criticism.
            $endgroup$
            – Peter Taylor
            Mar 4 at 13:01












            $begingroup$
            The constraints say that 1 <= d <= n, so yes, we have guarantees about d.
            $endgroup$
            – Astrinus
            Mar 5 at 8:12




            $begingroup$
            The constraints say that 1 <= d <= n, so yes, we have guarantees about d.
            $endgroup$
            – Astrinus
            Mar 5 at 8:12




            1




            1




            $begingroup$
            @Astrinus, if I wanted answers to those questions I'd have posted them as comments on the question. As I see it, one of the things a code review should do is challenge OP to think about whether they've fully understood the spec, and whether they can update the code if the spec (or their understanding of it) changes.
            $endgroup$
            – Peter Taylor
            Mar 5 at 8:30




            $begingroup$
            @Astrinus, if I wanted answers to those questions I'd have posted them as comments on the question. As I see it, one of the things a code review should do is challenge OP to think about whether they've fully understood the spec, and whether they can update the code if the spec (or their understanding of it) changes.
            $endgroup$
            – Peter Taylor
            Mar 5 at 8:30











            3












            $begingroup$

            You are focusing on the wrong portion of the problem. You're thinking the array needs to be rotated. The output of the array needs to be "rotated" but the array can remain as-is.



            So simply write a loop that starts at the middle of the array, incrementing until it hits the end, and then continues along from the beginning until it hits the index just before the one you started at.



            The output of that loop is the "rotated" array, from the visibility of the testing framework.



                string sep = "";
            for (int i = d % a.Length; i < a.Length; i++) {
            Console.Write(sep);
            Console.Write(a[i]);
            sep = " ";
            }
            for (int i = 0; i < d % a.Length; i++)
            {
            Console.Write(sep);
            Console.Write(a[i]);
            sep = " ";
            }


            This is a great reason why you should sometimes see hackerrank as a poor place to really learn programming.



            hackerrank primarily contains programming problems harvested from programming competitions. Competitions where these problems are meant to be solved fast, with a time deadline. This means that the problems are more about building a quick, clever, solution and less about really learning the lessons that would help you in a programming career.



            Another example of a solution is



                string sep = "";
            for (int i = d; a.Length + d - i > 0; i++) {
            Console.Write(sep);
            Console.Write(a[i % a.Length]);
            sep = " ";
            }


            Which is, according to hackerranks estimation, "just as good" as the above solution, but is far less readable.






            share|improve this answer











            $endgroup$









            • 1




              $begingroup$
              Well one thing one should certainly learn from this challenge is what string.Join does and how it avoids the rather awful for loop :) (The given solution also misses some necessary modulo ops)
              $endgroup$
              – Voo
              Mar 4 at 19:21












            • $begingroup$
              @Voo Out of curiosity, which modulo does this miss? I know I wrote it by hand without the aid of a computer, but the loop (in my 5 element example, starting at index 3 would be 3, 4, 5, 6, 7 (8 would be 5 + 3 - 8, so it wouldn't get there). and 3 % 5 = 3, 4 % 5 = 4, 5 % 5 = 0, 6 % 5 = 1, 7 % 5 = 2. Now, I just might have a bug in there after all; but, maybe not, which is a perfect example of why writing it this way is less than ideal and why hackerranks fascination with programming competitions as question banks is bad.
              $endgroup$
              – Edwin Buck
              Mar 4 at 20:20






            • 2




              $begingroup$
              You're supposed to do n rotations. Nowhere does it say that n < arr.Length. You could have an array of 1,2,3 and d=5. Both of your solutions fail with an out of bounds there.
              $endgroup$
              – Voo
              Mar 4 at 21:14






            • 1




              $begingroup$
              @Voo: if you read the challenge, you see that 1 <= d <= n, i.e. rotate an n elements array by d steps, so you cannot have more rotations than elements.
              $endgroup$
              – Astrinus
              Mar 5 at 8:15










            • $begingroup$
              @Voo I think you keep focusing on how (in my latter example) i is often out-of-range of the array. That's probably why you keep saying "out of bounds" which would cause an error if I was pulling out the i element of the array. But I'm not pulling i out of the array, I'm pulling i % a.Length which can't be out of bounds.
              $endgroup$
              – Edwin Buck
              Mar 5 at 17:10
















            3












            $begingroup$

            You are focusing on the wrong portion of the problem. You're thinking the array needs to be rotated. The output of the array needs to be "rotated" but the array can remain as-is.



            So simply write a loop that starts at the middle of the array, incrementing until it hits the end, and then continues along from the beginning until it hits the index just before the one you started at.



            The output of that loop is the "rotated" array, from the visibility of the testing framework.



                string sep = "";
            for (int i = d % a.Length; i < a.Length; i++) {
            Console.Write(sep);
            Console.Write(a[i]);
            sep = " ";
            }
            for (int i = 0; i < d % a.Length; i++)
            {
            Console.Write(sep);
            Console.Write(a[i]);
            sep = " ";
            }


            This is a great reason why you should sometimes see hackerrank as a poor place to really learn programming.



            hackerrank primarily contains programming problems harvested from programming competitions. Competitions where these problems are meant to be solved fast, with a time deadline. This means that the problems are more about building a quick, clever, solution and less about really learning the lessons that would help you in a programming career.



            Another example of a solution is



                string sep = "";
            for (int i = d; a.Length + d - i > 0; i++) {
            Console.Write(sep);
            Console.Write(a[i % a.Length]);
            sep = " ";
            }


            Which is, according to hackerranks estimation, "just as good" as the above solution, but is far less readable.






            share|improve this answer











            $endgroup$









            • 1




              $begingroup$
              Well one thing one should certainly learn from this challenge is what string.Join does and how it avoids the rather awful for loop :) (The given solution also misses some necessary modulo ops)
              $endgroup$
              – Voo
              Mar 4 at 19:21












            • $begingroup$
              @Voo Out of curiosity, which modulo does this miss? I know I wrote it by hand without the aid of a computer, but the loop (in my 5 element example, starting at index 3 would be 3, 4, 5, 6, 7 (8 would be 5 + 3 - 8, so it wouldn't get there). and 3 % 5 = 3, 4 % 5 = 4, 5 % 5 = 0, 6 % 5 = 1, 7 % 5 = 2. Now, I just might have a bug in there after all; but, maybe not, which is a perfect example of why writing it this way is less than ideal and why hackerranks fascination with programming competitions as question banks is bad.
              $endgroup$
              – Edwin Buck
              Mar 4 at 20:20






            • 2




              $begingroup$
              You're supposed to do n rotations. Nowhere does it say that n < arr.Length. You could have an array of 1,2,3 and d=5. Both of your solutions fail with an out of bounds there.
              $endgroup$
              – Voo
              Mar 4 at 21:14






            • 1




              $begingroup$
              @Voo: if you read the challenge, you see that 1 <= d <= n, i.e. rotate an n elements array by d steps, so you cannot have more rotations than elements.
              $endgroup$
              – Astrinus
              Mar 5 at 8:15










            • $begingroup$
              @Voo I think you keep focusing on how (in my latter example) i is often out-of-range of the array. That's probably why you keep saying "out of bounds" which would cause an error if I was pulling out the i element of the array. But I'm not pulling i out of the array, I'm pulling i % a.Length which can't be out of bounds.
              $endgroup$
              – Edwin Buck
              Mar 5 at 17:10














            3












            3








            3





            $begingroup$

            You are focusing on the wrong portion of the problem. You're thinking the array needs to be rotated. The output of the array needs to be "rotated" but the array can remain as-is.



            So simply write a loop that starts at the middle of the array, incrementing until it hits the end, and then continues along from the beginning until it hits the index just before the one you started at.



            The output of that loop is the "rotated" array, from the visibility of the testing framework.



                string sep = "";
            for (int i = d % a.Length; i < a.Length; i++) {
            Console.Write(sep);
            Console.Write(a[i]);
            sep = " ";
            }
            for (int i = 0; i < d % a.Length; i++)
            {
            Console.Write(sep);
            Console.Write(a[i]);
            sep = " ";
            }


            This is a great reason why you should sometimes see hackerrank as a poor place to really learn programming.



            hackerrank primarily contains programming problems harvested from programming competitions. Competitions where these problems are meant to be solved fast, with a time deadline. This means that the problems are more about building a quick, clever, solution and less about really learning the lessons that would help you in a programming career.



            Another example of a solution is



                string sep = "";
            for (int i = d; a.Length + d - i > 0; i++) {
            Console.Write(sep);
            Console.Write(a[i % a.Length]);
            sep = " ";
            }


            Which is, according to hackerranks estimation, "just as good" as the above solution, but is far less readable.






            share|improve this answer











            $endgroup$



            You are focusing on the wrong portion of the problem. You're thinking the array needs to be rotated. The output of the array needs to be "rotated" but the array can remain as-is.



            So simply write a loop that starts at the middle of the array, incrementing until it hits the end, and then continues along from the beginning until it hits the index just before the one you started at.



            The output of that loop is the "rotated" array, from the visibility of the testing framework.



                string sep = "";
            for (int i = d % a.Length; i < a.Length; i++) {
            Console.Write(sep);
            Console.Write(a[i]);
            sep = " ";
            }
            for (int i = 0; i < d % a.Length; i++)
            {
            Console.Write(sep);
            Console.Write(a[i]);
            sep = " ";
            }


            This is a great reason why you should sometimes see hackerrank as a poor place to really learn programming.



            hackerrank primarily contains programming problems harvested from programming competitions. Competitions where these problems are meant to be solved fast, with a time deadline. This means that the problems are more about building a quick, clever, solution and less about really learning the lessons that would help you in a programming career.



            Another example of a solution is



                string sep = "";
            for (int i = d; a.Length + d - i > 0; i++) {
            Console.Write(sep);
            Console.Write(a[i % a.Length]);
            sep = " ";
            }


            Which is, according to hackerranks estimation, "just as good" as the above solution, but is far less readable.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 5 at 19:33

























            answered Mar 4 at 19:19









            Edwin BuckEdwin Buck

            34415




            34415








            • 1




              $begingroup$
              Well one thing one should certainly learn from this challenge is what string.Join does and how it avoids the rather awful for loop :) (The given solution also misses some necessary modulo ops)
              $endgroup$
              – Voo
              Mar 4 at 19:21












            • $begingroup$
              @Voo Out of curiosity, which modulo does this miss? I know I wrote it by hand without the aid of a computer, but the loop (in my 5 element example, starting at index 3 would be 3, 4, 5, 6, 7 (8 would be 5 + 3 - 8, so it wouldn't get there). and 3 % 5 = 3, 4 % 5 = 4, 5 % 5 = 0, 6 % 5 = 1, 7 % 5 = 2. Now, I just might have a bug in there after all; but, maybe not, which is a perfect example of why writing it this way is less than ideal and why hackerranks fascination with programming competitions as question banks is bad.
              $endgroup$
              – Edwin Buck
              Mar 4 at 20:20






            • 2




              $begingroup$
              You're supposed to do n rotations. Nowhere does it say that n < arr.Length. You could have an array of 1,2,3 and d=5. Both of your solutions fail with an out of bounds there.
              $endgroup$
              – Voo
              Mar 4 at 21:14






            • 1




              $begingroup$
              @Voo: if you read the challenge, you see that 1 <= d <= n, i.e. rotate an n elements array by d steps, so you cannot have more rotations than elements.
              $endgroup$
              – Astrinus
              Mar 5 at 8:15










            • $begingroup$
              @Voo I think you keep focusing on how (in my latter example) i is often out-of-range of the array. That's probably why you keep saying "out of bounds" which would cause an error if I was pulling out the i element of the array. But I'm not pulling i out of the array, I'm pulling i % a.Length which can't be out of bounds.
              $endgroup$
              – Edwin Buck
              Mar 5 at 17:10














            • 1




              $begingroup$
              Well one thing one should certainly learn from this challenge is what string.Join does and how it avoids the rather awful for loop :) (The given solution also misses some necessary modulo ops)
              $endgroup$
              – Voo
              Mar 4 at 19:21












            • $begingroup$
              @Voo Out of curiosity, which modulo does this miss? I know I wrote it by hand without the aid of a computer, but the loop (in my 5 element example, starting at index 3 would be 3, 4, 5, 6, 7 (8 would be 5 + 3 - 8, so it wouldn't get there). and 3 % 5 = 3, 4 % 5 = 4, 5 % 5 = 0, 6 % 5 = 1, 7 % 5 = 2. Now, I just might have a bug in there after all; but, maybe not, which is a perfect example of why writing it this way is less than ideal and why hackerranks fascination with programming competitions as question banks is bad.
              $endgroup$
              – Edwin Buck
              Mar 4 at 20:20






            • 2




              $begingroup$
              You're supposed to do n rotations. Nowhere does it say that n < arr.Length. You could have an array of 1,2,3 and d=5. Both of your solutions fail with an out of bounds there.
              $endgroup$
              – Voo
              Mar 4 at 21:14






            • 1




              $begingroup$
              @Voo: if you read the challenge, you see that 1 <= d <= n, i.e. rotate an n elements array by d steps, so you cannot have more rotations than elements.
              $endgroup$
              – Astrinus
              Mar 5 at 8:15










            • $begingroup$
              @Voo I think you keep focusing on how (in my latter example) i is often out-of-range of the array. That's probably why you keep saying "out of bounds" which would cause an error if I was pulling out the i element of the array. But I'm not pulling i out of the array, I'm pulling i % a.Length which can't be out of bounds.
              $endgroup$
              – Edwin Buck
              Mar 5 at 17:10








            1




            1




            $begingroup$
            Well one thing one should certainly learn from this challenge is what string.Join does and how it avoids the rather awful for loop :) (The given solution also misses some necessary modulo ops)
            $endgroup$
            – Voo
            Mar 4 at 19:21






            $begingroup$
            Well one thing one should certainly learn from this challenge is what string.Join does and how it avoids the rather awful for loop :) (The given solution also misses some necessary modulo ops)
            $endgroup$
            – Voo
            Mar 4 at 19:21














            $begingroup$
            @Voo Out of curiosity, which modulo does this miss? I know I wrote it by hand without the aid of a computer, but the loop (in my 5 element example, starting at index 3 would be 3, 4, 5, 6, 7 (8 would be 5 + 3 - 8, so it wouldn't get there). and 3 % 5 = 3, 4 % 5 = 4, 5 % 5 = 0, 6 % 5 = 1, 7 % 5 = 2. Now, I just might have a bug in there after all; but, maybe not, which is a perfect example of why writing it this way is less than ideal and why hackerranks fascination with programming competitions as question banks is bad.
            $endgroup$
            – Edwin Buck
            Mar 4 at 20:20




            $begingroup$
            @Voo Out of curiosity, which modulo does this miss? I know I wrote it by hand without the aid of a computer, but the loop (in my 5 element example, starting at index 3 would be 3, 4, 5, 6, 7 (8 would be 5 + 3 - 8, so it wouldn't get there). and 3 % 5 = 3, 4 % 5 = 4, 5 % 5 = 0, 6 % 5 = 1, 7 % 5 = 2. Now, I just might have a bug in there after all; but, maybe not, which is a perfect example of why writing it this way is less than ideal and why hackerranks fascination with programming competitions as question banks is bad.
            $endgroup$
            – Edwin Buck
            Mar 4 at 20:20




            2




            2




            $begingroup$
            You're supposed to do n rotations. Nowhere does it say that n < arr.Length. You could have an array of 1,2,3 and d=5. Both of your solutions fail with an out of bounds there.
            $endgroup$
            – Voo
            Mar 4 at 21:14




            $begingroup$
            You're supposed to do n rotations. Nowhere does it say that n < arr.Length. You could have an array of 1,2,3 and d=5. Both of your solutions fail with an out of bounds there.
            $endgroup$
            – Voo
            Mar 4 at 21:14




            1




            1




            $begingroup$
            @Voo: if you read the challenge, you see that 1 <= d <= n, i.e. rotate an n elements array by d steps, so you cannot have more rotations than elements.
            $endgroup$
            – Astrinus
            Mar 5 at 8:15




            $begingroup$
            @Voo: if you read the challenge, you see that 1 <= d <= n, i.e. rotate an n elements array by d steps, so you cannot have more rotations than elements.
            $endgroup$
            – Astrinus
            Mar 5 at 8:15












            $begingroup$
            @Voo I think you keep focusing on how (in my latter example) i is often out-of-range of the array. That's probably why you keep saying "out of bounds" which would cause an error if I was pulling out the i element of the array. But I'm not pulling i out of the array, I'm pulling i % a.Length which can't be out of bounds.
            $endgroup$
            – Edwin Buck
            Mar 5 at 17:10




            $begingroup$
            @Voo I think you keep focusing on how (in my latter example) i is often out-of-range of the array. That's probably why you keep saying "out of bounds" which would cause an error if I was pulling out the i element of the array. But I'm not pulling i out of the array, I'm pulling i % a.Length which can't be out of bounds.
            $endgroup$
            – Edwin Buck
            Mar 5 at 17:10











            1












            $begingroup$



            • Because of the 2 imbricated for loops in the original code,



              for (int intI = 0; intI < d; intI++) {

              for (int intK = 0; intK < a.Length; intK++) {
              ...
              }
              }




            your code performs d * a.Length actions. Which takes quadratic time when d is near a.Length/2.



            So, we may ask, can we do better ?





            • The answer is yes. There is a linear-time solution. It is as follows :




              1. "mirror" the first d elements

              2. mirror the whole array

              3. mirror the size-d first elements.




            Implementation of mirror (rever an array) is left to the reader.



            Linear time complexity. 0(1) extra room needed (loop variable and temporary for exchange).



            So it is clearly an improvement on the original version.






            share|improve this answer











            $endgroup$













            • $begingroup$
              You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
              $endgroup$
              – Toby Speight
              Mar 5 at 11:02
















            1












            $begingroup$



            • Because of the 2 imbricated for loops in the original code,



              for (int intI = 0; intI < d; intI++) {

              for (int intK = 0; intK < a.Length; intK++) {
              ...
              }
              }




            your code performs d * a.Length actions. Which takes quadratic time when d is near a.Length/2.



            So, we may ask, can we do better ?





            • The answer is yes. There is a linear-time solution. It is as follows :




              1. "mirror" the first d elements

              2. mirror the whole array

              3. mirror the size-d first elements.




            Implementation of mirror (rever an array) is left to the reader.



            Linear time complexity. 0(1) extra room needed (loop variable and temporary for exchange).



            So it is clearly an improvement on the original version.






            share|improve this answer











            $endgroup$













            • $begingroup$
              You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
              $endgroup$
              – Toby Speight
              Mar 5 at 11:02














            1












            1








            1





            $begingroup$



            • Because of the 2 imbricated for loops in the original code,



              for (int intI = 0; intI < d; intI++) {

              for (int intK = 0; intK < a.Length; intK++) {
              ...
              }
              }




            your code performs d * a.Length actions. Which takes quadratic time when d is near a.Length/2.



            So, we may ask, can we do better ?





            • The answer is yes. There is a linear-time solution. It is as follows :




              1. "mirror" the first d elements

              2. mirror the whole array

              3. mirror the size-d first elements.




            Implementation of mirror (rever an array) is left to the reader.



            Linear time complexity. 0(1) extra room needed (loop variable and temporary for exchange).



            So it is clearly an improvement on the original version.






            share|improve this answer











            $endgroup$





            • Because of the 2 imbricated for loops in the original code,



              for (int intI = 0; intI < d; intI++) {

              for (int intK = 0; intK < a.Length; intK++) {
              ...
              }
              }




            your code performs d * a.Length actions. Which takes quadratic time when d is near a.Length/2.



            So, we may ask, can we do better ?





            • The answer is yes. There is a linear-time solution. It is as follows :




              1. "mirror" the first d elements

              2. mirror the whole array

              3. mirror the size-d first elements.




            Implementation of mirror (rever an array) is left to the reader.



            Linear time complexity. 0(1) extra room needed (loop variable and temporary for exchange).



            So it is clearly an improvement on the original version.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 29 at 16:49

























            answered Mar 4 at 9:05









            Michel BillaudMichel Billaud

            1814




            1814












            • $begingroup$
              You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
              $endgroup$
              – Toby Speight
              Mar 5 at 11:02


















            • $begingroup$
              You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
              $endgroup$
              – Toby Speight
              Mar 5 at 11:02
















            $begingroup$
            You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
            $endgroup$
            – Toby Speight
            Mar 5 at 11:02




            $begingroup$
            You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
            $endgroup$
            – Toby Speight
            Mar 5 at 11:02


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214680%2fhacker-rank-array-left-rotation%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Aardman Animations

            Are they similar matrix

            “minimization” problem in Euclidean space related to orthonormal basis