Rotated Array Lookup Plus Most Common Values
Heaps, Sorting & SearchAuto-graded · 22 test casesLast updated
Find a value's index in a rotated sorted array with binary search, then list the k most frequent values with ties broken by smaller value.
Rotated Lookup and Frequency Ranking
A list of integers was originally sorted in non-decreasing order. It was then rotated at some unknown position, so a prefix of the sorted list was moved to the end. For example, [0, 1, 2, 4, 5, 6, 7] could become [4, 5, 6, 7, 0, 1, 2]. A list that was not rotated at all is also a valid input.
Implement one function that answers two questions about nums.
Question 1: position of a value. Return the index at which target appears in nums, or -1 if it is absent. You can assume target occurs at most once in nums. Aim for logarithmic time on this part.
Question 2: most common values. Find the k values that occur most often in nums. Order them as follows:
- Values with a higher occurrence count come first.
- Values with equal counts are ordered by value, smaller first.
Return a two-element list [index, top_values], where index is the answer to Question 1 and top_values is the ordered list of k values from Question 2.
Constraints
1 <= len(nums) <= 10^5-10^4 <= nums[i] <= 10^41 <= k <=the number of distinct values innumstargetoccurs at most once innums- The result is always
[index, top_values], withindex = -1whentargetis not found
Edge cases to handle
numshas a single element.numsis not rotated.- All elements are equal (then
k = 1). targetis smaller or larger than every element.
Examples
Example 1
Input: rotated_find_and_frequent([4, 5, 6, 7, 0, 1, 2], 0, 2)
Output: [4, [0, 1]]
Example 2
Input: rotated_find_and_frequent([1, 1, 1, 2, 2, 3], 3, 2)
Output: [5, [1, 2]]
Hints
Hint 1
In a rotated sorted array, at every midpoint at least one of the two halves is fully sorted. Compare the endpoint with the midpoint to find which one.
Hint 2
Once you know which half is sorted, check whether the target lies within that half's value range. If it does, keep that half. Otherwise keep the other one.
Hint 3
For the frequency part, count values with a hash map, then sort the distinct values by the key (negative count, value) and take the first k.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two questions are independent, so we solve them one after the other and return both answers.
Finding the target
A rotated sorted array has only one place where the order "drops". At any midpoint mid, that drop lies in at most one of the halves [lo..mid] and [mid..hi], so the other half is fully sorted.
- If
nums[mid] == target, we are done. - If
nums[lo] <= nums[mid], the left half is sorted. Ifnums[lo] <= target < nums[mid], the target can only be in the left half, so sethi = mid - 1. Otherwise setlo = mid + 1. - Otherwise the right half is sorted. If
nums[mid] < target <= nums[hi], setlo = mid + 1. Otherwise sethi = mid - 1.
This is correct because a sorted half has known bounds, so the range check decides exactly whether the target can be inside it. If it cannot, it can only be in the other half. Each step discards a half that cannot contain the target, so the loop invariant "if the target exists, it lies in [lo, hi]" is preserved. An empty range means the target is absent, and we return -1.
Ranking by frequency
Count every value with a hash map. Then sort the distinct values by the key (-count, value). This puts higher counts first and breaks ties with the smaller value, which gives a fully deterministic order. The first k entries are the answer.
Complexity
- Search: O(log n) time and O(1) space.
- Counting: O(n) time and O(u) space, where
uis the number of distinct values. - Sorting the distinct values: O(u log u) time.
- Overall: O(n + u log u) time and O(u) extra space.
Reference solution
from collections import Counter
from typing import List
def rotated_find_and_frequent(nums: List[int], target: int, k: int) -> List[object]:
lo, hi = 0, len(nums) - 1
index = -1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
index = mid
break
if nums[lo] <= nums[mid]:
# left half is sorted
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else:
# right half is sorted
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
counts = Counter(nums)
top = sorted(counts, key=lambda value: (-counts[value], value))[:k]
return [index, top]