From 41ff6c0a8709fb082cde6f20e4be5d73bc57ad8e Mon Sep 17 00:00:00 2001 From: nirmalya8 Date: Sun, 3 Oct 2021 14:37:06 +0530 Subject: [PATCH 1/2] Added script in JAVA for how many times an array has been rotated in O(log n) time --- Searches/howManyTimesRotated.java | 65 +++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Searches/howManyTimesRotated.java diff --git a/Searches/howManyTimesRotated.java b/Searches/howManyTimesRotated.java new file mode 100644 index 000000000000..19fd5077869f --- /dev/null +++ b/Searches/howManyTimesRotated.java @@ -0,0 +1,65 @@ +/* + Problem Statement: + Given an array, find out how many times it has to been rotated + from its initial sorted position. + Input-Output: + Eg. [11,12,15,18,2,5,6,8] + It has been rotated: 4 times + (One rotation means putting the first element to the end) + + Logic: + The position of the minimum element will give the number of times the array has been rotated + from its initial sorted position. + Eg. For [2,5,6,8,11,12,15,18], 1 rotation gives [5,6,8,11,12,15,18,2], 2 rotations [6,8,11,12,15,18,2,5] and so on. + Finding the minimum element will take O(N) time but, we can use Binary Search to find the mimimum element, we can reduce the complexity to O(log N). + If we look at the rotated array, to identify the minimum element (say a[i]), we observe that a[i-1]>a[i]a[mid-1] && a[mid]a[mid-1] && a[mid]>a[mid+1]) + { + low = mid-1; + } + } + + return mid; + } +} \ No newline at end of file From dc25cd5f5daf0863cd581e09d780964cb6164070 Mon Sep 17 00:00:00 2001 From: Nirmalya Misra <39618712+nirmalya8@users.noreply.github.com> Date: Mon, 4 Oct 2021 11:14:15 +0530 Subject: [PATCH 2/2] Added the no duplicates constraint --- Searches/howManyTimesRotated.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Searches/howManyTimesRotated.java b/Searches/howManyTimesRotated.java index 19fd5077869f..487df2e51d99 100644 --- a/Searches/howManyTimesRotated.java +++ b/Searches/howManyTimesRotated.java @@ -6,6 +6,7 @@ Eg. [11,12,15,18,2,5,6,8] It has been rotated: 4 times (One rotation means putting the first element to the end) + Note: The array cannot contain duplicates Logic: The position of the minimum element will give the number of times the array has been rotated @@ -62,4 +63,4 @@ else if(a[mid]>a[mid-1] && a[mid]>a[mid+1]) return mid; } -} \ No newline at end of file +}