A geology lab drills a long sediment core and records the mineral code of every sample taken along its length. The n mineral codes are handed to you already sorted in non-decreasing order, exactly as the lab's spectrometer streams them out. The lead geologist suspects that one particular mineral code, target, dominates the core -- meaning it accounts for strictly more than half of all n samples -- and wants this confirmed without scanning the whole core by hand, since a single core can hold hundreds of thousands of readings. Because the list is sorted, every occurrence of target is guaranteed to sit in one contiguous block, so its first and last position can be located with a search that never touches most of the array.
Write a program that reports whether target is a strict-majority code of the core.
Line 1: a single integer n, the number of samples.
Line 2: n integers separated by spaces, the mineral codes in non-decreasing order.
Line 3: a single integer target, the mineral code being tested.
Print true if target occurs strictly more than n / 2 times among the samples, otherwise print false.
Example 1
Input
7 2 2 4 4 4 4 6 4
Expected
true
Explanation
Among the 7 sorted codes, mineral code 4 appears 4 times (positions 3 through 6). Since 4*2=8 is strictly greater than 7, code 4 is a majority code, so the answer is true.
Example 2
Input
5 1 2 3 4 5 3
Expected
false
Explanation
Mineral code 3 appears only once among the 5 samples. Since 1*2=2 is not greater than 5, it is not a majority code, so the answer is false.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →