Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Firstly, I will make a big assumption that "better" means "I do not want any/as few new data structures".</p> <p>If this is the case, then the simplest solution is the best, since I don't need to bother optimising by time. I know that the other solutions are much more elegant, I've only posted it because I've read the question as "make sure it's minimal space-wise".</p> <pre><code>private static String rotate( final char[] a, final int n ) { for(int i = 0; i &lt; n; i++) { char tmp = a[a.length-1]; for(int j = a.length-1; j &gt;= 0; j--) { a[j] = j == 0 ? tmp : a[(j-1+a.length)%a.length]; } } return new String(a); } </code></pre> <p>So I hacked this out pretty quickly. Basically, I'm just doing rotates by lengths of one until I've rotated <code>n</code> number of times. To optimise it you probably could take <code>gcd(n, a.length)</code>.</p> <p>Now, since my solution is pretty terrible, I'll also post the following code taken from <a href="http://www.leetcode.com/2010/04/rotating-array-in-place.html" rel="noreferrer">here</a></p> <pre><code>void reverse_string(char* str, int left, int right) { char* p1 = str + left; char* p2 = str + right; while (p1 &lt; p2) { char temp = *p1; *p1 = *p2; *p2 = temp; p1++; p2--; } } void rotate(char* str, int k) { int n = strlen(str); reverse_string(str, 0, n-1); reverse_string(str, 0, k-1); reverse_string(str, k, n-1); } </code></pre> <p>This is, what I assume to be a C-style implementation that runs faster than mine, using a basic idea that with three reverses, you can implement an inline shift.</p> <p>As is said here,</p> <blockquote> <p>The trick is to do three reverse operation. One for the entire string, one from index 0 to k-1, and lastly index k to n-1. Magically, this will yield the correct rotated array, without any extra space! (Of course, you need a temporary variable for swapping).</p> </blockquote> <p>I haven't verified this property on the blog I've linked to, so I will post it with a grain of salt that it would appear to work but I've never tested it myself...</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload