Problem
Write a function to rotate given array clock-wise. i.e. Rotate(int[] a, int k)Approaches
1. One obvious approach is by using extra memory of 'k', and then rotating the array - it is O(N) and O(k) space.
2. Rotating array by '1' and repeating the task for 'k' number of times
Below is the approach of achieving the result in O(N) and O(1) space:
a. Firstly, reverse the array
b. And then reverse first 'k' elements and reverse remaining elements separately.
Code Snippet
- void swap<T>(ref T x, ref T y)
- {
- T t = x;
- x = y;
- y = t;
- }
- void Reverse(int[] a, int start, int end)
- {
- int i = start, j = end;
- while (i < j)
- {
- swap<int>(ref a[i], ref a[j]);
- i++;
- j--;
- }
- }
- void Rotate(int[] a, int k)
- {
- a.ThrowIfNull("array");
- k.Throw("k", e => e < 0);
- if (a.Length <= 1)
- {
- return;
- }
- k = k % a.Length;
- this.Reverse(a, 0, a.Length - 1);
- this.Reverse(a, 0, k - 1);
- this.Reverse(a, k, a.Length - 1);
- }
Unit Tests
Code Snippet
- [TestMethod]
- public void RotateTests()
- {
- int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
- for (int i = 1; i <= a.Length; i++)
- {
- int k = a.Length - i + 1;
- int[] b = new int[a.Length];
- this.Rotate(a, i);
- for(int j = 0;j<b.Length;j++)
- {
- if(k > a.Length)
- {
- k = (k % a.Length);
- }
- b[j] = k;
- k++;
- }
- for (int j = 0; j < a.Length;j++ )
- {
- Assert.IsTrue(a[j] == b[j]);
- }
- this.Rotate(a, a.Length - i);
- }
- }
No comments:
Post a Comment