We are given a sorted rotated array containing distinct non-negative integers and a number x. The task is to count all elements that are less than or equal to x.
A rotated array is an array that was originally sorted in ascending order and then rotated at some pivot.
Example
Original Array
[1, 3, 4, 5, 8]
Rotated Array
[4, 5, 8, 1, 3]
Problem Understanding
Input
arr = [4, 5, 8, 1, 3]
x = 6
Elements ≤ 6
1, 3, 4, 5
Count
4
Naive Approach
We can scan the array and count the elements that satisfy the condition.
count = 0
for i = 0 to n - 1:
if arr[i] <= x:
count++
Time Complexity
O(n)
However, the array is sorted before rotation, so we can do better using binary search.
Efficient Approach (O(log n))
Key Idea
A rotated sorted array consists of two sorted subarrays.
For example:
[4, 5, 8] and [1, 3]
If we can find the pivot (the index of the smallest element), we can split the array into two sorted ranges.
Then we can perform binary search in both ranges to count elements less than or equal to x.
Step 1: Find the Pivot
The pivot is the index of the smallest element.
Cases
If the array is not rotated, pivot = 0.
Otherwise, the pivot separates the two sorted segments.
Binary Search for Pivot
low = 0
high = n - 1
while low < high:
mid = low + (high - low) / 2
if arr[mid] > arr[high]:
low = mid + 1
else:
high = mid
pivot = low
Complexity
O(log n)
Step 2: Binary Search in Both Sorted Segments
After finding the pivot:
Left Segment:
arr[pivot ... n - 1]Right Segment:
arr[0 ... pivot - 1]
Count elements less than or equal to x in both segments separately.
Binary Search for Counting Elements ≤ x
function countLessEqualSorted(arr, low, high, x):
ans = -1
while low <= high:
mid = low + (high - low) / 2
if arr[mid] <= x:
ans = mid
low = mid + 1
else:
high = mid - 1
return ans - startIndex + 1
Observation
ansstores the last index wherearr[mid] ≤ x.Number of valid elements:
ans - startIndex + 1

Join the conversation! Your thoughts help the community grow.