call(back)
Algorithms & Data StructuresmediumSign in to star problems

More Than a Third in a Sorted Array

Given an array nums sorted in non-decreasing order, return every value that appears more than nums.length / 3 times, in increasing order.

frequentInSorted([1, 2, 3])              ->  []
frequentInSorted([1, 1, 2, 3, 4])        ->  [1]
frequentInSorted([1, 1, 2, 4, 4])        ->  [1, 4]
frequentInSorted([1, 2, 3, 4, 5, 6, 7])  ->  []

A linear scan is the baseline. The follow-up asks for better than O(n) by using the fact that the array is sorted.

Hints

Hint 1

Equal values are contiguous, so a value that qualifies is one run longer than n / 3.

Hint 2

A run that long cannot fit strictly before index floor(n / 3), strictly between that index and floor(2n / 3), or strictly after it. So it contains one of those two indices.

Hint 3

For each of the two candidate values, binary-search its first and last position and compare the run length with n / 3.

Topics

Asked at

Similar Problems6