diff --git a/Pattern11 - Modified Binary Search/Challenge3-Rotation_Count/solution.go b/Pattern11 - Modified Binary Search/Challenge3-Rotation_Count/solution.go new file mode 100644 index 0000000..2317566 --- /dev/null +++ b/Pattern11 - Modified Binary Search/Challenge3-Rotation_Count/solution.go @@ -0,0 +1,47 @@ +package challenge3rotationcount + +/* +Given an array of numbers which is sorted in ascending order and is rotated ‘k’ times around a pivot, find ‘k’. + +You can assume that the array does not have any duplicates. + +Input: [10, 15, 1, 3, 8] +Output: 2 +Explanation: The array has been rotated 2 times. + +Input: [4, 5, 7, 9, 10, -1, 2] +Output: 5 +Explanation: The array has been rotated 5 times. + +Input: [1, 3, 8, 10] +Output: 0 +Explanation: The array has been not been rotated. + +ref: https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/ +*/ + +func countRotations(arr []int) int { + var ( + start = 0 + end = len(arr) - 1 + ) + + for start < end { + mid := start + (end-start)/2 + if mid < end && arr[mid] > arr[mid+1] { + return mid + 1 + } + if mid > start && arr[mid-1] > arr[mid] { + return mid + } + + if arr[start] < arr[mid] { + // left part sorted, so pivot is right part + start = mid + 1 + } else { + end = mid - 1 + } + } + + return 0 +} diff --git a/Pattern11 - Modified Binary Search/Challenge3-Rotation_Count/solution_test.go b/Pattern11 - Modified Binary Search/Challenge3-Rotation_Count/solution_test.go new file mode 100644 index 0000000..a8c5393 --- /dev/null +++ b/Pattern11 - Modified Binary Search/Challenge3-Rotation_Count/solution_test.go @@ -0,0 +1,26 @@ +package challenge3rotationcount + +import "testing" + +func Test_countRotations(t *testing.T) { + type args struct { + arr []int + } + tests := []struct { + name string + args args + want int + }{ + {"case1", args{[]int{10, 15, 1, 3, 8}}, 2}, + {"case2", args{[]int{4, 5, 7, 9, 10, -1, 2}}, 5}, + {"case3", args{[]int{1, 3, 8, 10}}, 0}, + {"case4", args{[]int{10, 1, 3, 8, 9}}, 1}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := countRotations(tt.args.arr); got != tt.want { + t.Errorf("countRotations() = %v, want %v", got, tt.want) + } + }) + } +}