Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Find How Many Times a Sorted Array Has Been Rotated
Optimal Binary Search



Problem Statement

Given a sorted and rotated array of distinct integers, your task is to determine the number of times the array has been rotated.

Your goal is to find the index of the smallest element in the array, as this index represents the number of rotations.

If the array is empty, return -1.

Examples

Input ArrayRotation CountDescription
[15, 18, 2, 3, 6, 12]2Array was rotated 2 times. The smallest element 2 is at index 2.
[7, 9, 11, 12, 5]4Array was rotated 4 times. 5 is the smallest element at index 4.
[1, 2, 3, 4, 5]0No rotation. Array is already sorted.
[3, 4, 5, 1, 2]3Array rotated 3 times. Smallest element 1 at index 3.
[2]0Single element array, considered already sorted.
[]-1Empty array, so no rotation count can be determined.

Solution

To find out how many times a sorted array has been rotated, we can look for the position of the smallest element in the array. This works because, in a rotated sorted array, the smallest element is the point of rotation — and its index equals the rotation count.

Case 1: Array is not rotated at all
In this case, the array remains fully sorted in increasing order. So, the smallest element is at index 0. That means the rotation count is 0.

Case 2: Array has been rotated
If the array has been rotated, the smallest element will appear somewhere after the beginning. The number of steps we had to rotate to get to this state is the index where the smallest element now resides.

For example, in [15, 18, 2, 3, 6, 12], the smallest element is 2 at index 2, meaning the array was rotated 2 times.

Case 3: Empty array
If the array has no elements, there's no rotation to count, and we return -1 to indicate this is not a valid input for rotation logic.

Case 4: Single element
In an array like [2], there’s only one element, which is already the smallest and largest at the same time. So, we return 0 as no rotation is needed or detectable.

By using binary search, we can efficiently find the index of the smallest element, which directly tells us the rotation count — all in O(log n) time, making it much faster than checking every element one by one.

Visualization

Algorithm Steps

  1. Initialize start = 0, end = n - 1.
  2. While start ≤ end:
  3. → If arr[start] ≤ arr[end], the subarray is already sorted, so return start.
  4. → Calculate mid = start + (end - start) / 2.
  5. → Calculate prev = (mid - 1 + n) % n and next = (mid + 1) % n.
  6. → If arr[mid] ≤ arr[prev] and arr[mid] ≤ arr[next], return mid.
  7. → If arr[mid] ≥ arr[start], search in the right half: start = mid + 1.
  8. → Else, search in the left half: end = mid - 1.

Code

Java
Python
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
public class RotationCountFinder {
  public static int findRotationCount(int[] arr) {
    int n = arr.length;
    int start = 0, end = n - 1;

    while (start <= end) {
      if (arr[start] <= arr[end]) return start; // Sorted, minimum at start

      int mid = start + (end - start) / 2;
      int next = (mid + 1) % n;
      int prev = (mid - 1 + n) % n;

      if (arr[mid] <= arr[prev] && arr[mid] <= arr[next])
        return mid; // Found the pivot

      else if (arr[mid] >= arr[start])
        start = mid + 1; // Search right
      else
        end = mid - 1; // Search left
    }

    return 0; // Not rotated
  }

  public static void main(String[] args) {
    int[] arr = {15, 18, 2, 3, 6, 12};
    System.out.println("Rotation Count: " + findRotationCount(arr));
  }
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)When the array is not rotated, the first check detects it immediately.
Average CaseO(log n)Each iteration eliminates half the search space by applying binary search logic.
Average CaseO(log n)In the worst case, the search continues until the pivot element is found using binary search.

Space Complexity

O(1)

Explanation: Only a constant number of variables (start, end, mid, next, prev) are used for the search.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M