Skip to content

Commit

Permalink
day 197: rotate slice right by k
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Mar 8, 2019
1 parent e683d6a commit 7dca9b4
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
16 changes: 16 additions & 0 deletions day197/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package day197

// RotateRightK rotates the nums slice in-place to the right.
// Runs in O(N) time and O(1) space.
func RotateRightK(nums []int, k int) {
k %= len(nums)
for i := 0; i < k/2; i++ {
nums[i], nums[k-1-i] = nums[k-1-i], nums[i]
}
for i := 0; i < (len(nums)-k)/2; i++ {
nums[k+i], nums[len(nums)-1-i] = nums[len(nums)-1-i], nums[k+i]
}
for i := 0; i < len(nums)/2; i++ {
nums[i], nums[len(nums)-1-i] = nums[len(nums)-1-i], nums[i]
}
}
34 changes: 34 additions & 0 deletions day197/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package day197

import (
"reflect"
"testing"
)

var testcases = []struct {
nums []int
k int
expected []int
}{
{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 4, []int{5, 6, 7, 8, 9, 10, 1, 2, 3, 4}},
}

func TestRotateRightK(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
result := append([]int{}, tc.nums...)
RotateRightK(result, tc.k)
if !reflect.DeepEqual(result, tc.expected) {
t.Errorf("Expected %v, got %v", tc.expected, result)
}
}
}

func BenchmarkRotateRightK(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
result := append([]int{}, tc.nums...)
RotateRightK(result, tc.k)
}
}
}

0 comments on commit 7dca9b4

Please sign in to comment.