Hacker Rank: Array left rotation












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









New contributor




Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$

















    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









    New contributor




    Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      3












      3








      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









      New contributor




      Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $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









      New contributor




      Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 30 mins ago









      Toby Speight

      25.3k742116




      25.3k742116






      New contributor




      Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 3 hours ago









      RamakrishnaRamakrishna

      184




      184




      New contributor




      Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          4 Answers
          4






          active

          oldest

          votes


















          4












          $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$





















            3












            $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$





















              3












              $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$





















                0












                $begingroup$


                1. "mirror" the first d elements

                2. mirror the whole array

                3. mirror the size-d first elements.


                In place. Linear time complexity. 0(1) extra room needed.






                share|improve this answer









                $endgroup$













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


                  }
                  });






                  Ramakrishna is a new contributor. Be nice, and check out our Code of Conduct.










                  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

























                  4 Answers
                  4






                  active

                  oldest

                  votes








                  4 Answers
                  4






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  4












                  $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$


















                    4












                    $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$
















                      4












                      4








                      4





                      $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 38 mins ago









                      t3chb0tt3chb0t

                      34.7k751121




                      34.7k751121

























                          3












                          $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$


















                            3












                            $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$
















                              3












                              3








                              3





                              $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 54 mins ago

























                              answered 1 hour ago









                              Henrik HansenHenrik Hansen

                              7,52511128




                              7,52511128























                                  3












                                  $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$


















                                    3












                                    $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$
















                                      3












                                      3








                                      3





                                      $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 39 mins ago









                                      Peter TaylorPeter Taylor

                                      17.4k2862




                                      17.4k2862























                                          0












                                          $begingroup$


                                          1. "mirror" the first d elements

                                          2. mirror the whole array

                                          3. mirror the size-d first elements.


                                          In place. Linear time complexity. 0(1) extra room needed.






                                          share|improve this answer









                                          $endgroup$


















                                            0












                                            $begingroup$


                                            1. "mirror" the first d elements

                                            2. mirror the whole array

                                            3. mirror the size-d first elements.


                                            In place. Linear time complexity. 0(1) extra room needed.






                                            share|improve this answer









                                            $endgroup$
















                                              0












                                              0








                                              0





                                              $begingroup$


                                              1. "mirror" the first d elements

                                              2. mirror the whole array

                                              3. mirror the size-d first elements.


                                              In place. Linear time complexity. 0(1) extra room needed.






                                              share|improve this answer









                                              $endgroup$




                                              1. "mirror" the first d elements

                                              2. mirror the whole array

                                              3. mirror the size-d first elements.


                                              In place. Linear time complexity. 0(1) extra room needed.







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered 17 mins ago









                                              Michel BillaudMichel Billaud

                                              1554




                                              1554






















                                                  Ramakrishna is a new contributor. Be nice, and check out our Code of Conduct.










                                                  draft saved

                                                  draft discarded


















                                                  Ramakrishna is a new contributor. Be nice, and check out our Code of Conduct.













                                                  Ramakrishna is a new contributor. Be nice, and check out our Code of Conduct.












                                                  Ramakrishna is a new contributor. Be nice, and check out our Code of Conduct.
















                                                  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

                                                  Liste der Baudenkmäler in Partschins

                                                  Sámuel Mokry

                                                  Valadolido