KatInterview

Rotated Array Lookup Plus Most Common Values

Heaps, Sorting & SearchAuto-graded · 22 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchrotated-arrayhash-map

Last 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:

  1. Values with a higher occurrence count come first.
  2. 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^4
  • 1 <= k <= the number of distinct values in nums
  • target occurs at most once in nums
  • The result is always [index, top_values], with index = -1 when target is not found

Edge cases to handle

  • nums has a single element.
  • nums is not rotated.
  • All elements are equal (then k = 1).
  • target is 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.