Find out how many times the array is rotated

Binary Search Logic Building Easy

Given an integer array nums of size n, sorted in ascending order with distinct values. The array has been right rotated an unknown number of times, between 1 and n. Determine the number of rotations performed on the array.

Examples:

Input : nums = [4, 5, 6, 7, 0, 1, 2, 3]

Output: 4

Explanation: The original array should be [0, 1, 2, 3, 4, 5, 6, 7]. So, we can notice that the array has been rotated 4 times.

Input: nums = [3, 4, 5, 1, 2]

Output: 3

Explanation: The original array should be [1, 2, 3, 4, 5]. So, we can notice that the array has been rotated 3 times.

Input: nums = [4, 5, 1, 2]

Constraints

  •  n == nums.length
  •  1 <= n <= 104
  •  -104 <= nums[i] <= 104
  •  All the integers of nums are unique.

Hints

  • The rotation count is equivalent to the index of the smallest element (pivot) in the rotated sorted array.
  • "Use binary search to locate the smallest element (pivot) efficiently: If nums[mid] > nums[high], the pivot lies in the right half. Update low = mid + 1. If nums[mid] <= nums[high], the pivot lies in the left half or is the middle element itself. Update high = mid."

Company Tags

PwC Philips Healthcare Airbnb Byju's HCL Technologies ARM Pinterest Riot Games Splunk Goldman Sachs Boston Consulting Group Oracle Docker Johnson & Johnson Siemens Healthineers Nutanix Roblox Deloitte Databricks Intel Zoho Chewy Epic Games Unity Technologies Salesforce TCS Cognizant Accenture Infosys Capgemini Wipro