1473. Dominant Reading Check

Easy1.5 points estimatedBinary SearchArrayCounting

A sensor logs temperature readings in nums, sorted in non-decreasing order. A value x is called dominant when it appears in more than half of all the readings, that is when twice its number of occurrences is greater than nums.length.

Return true if x is dominant and false otherwise; a value that does not occur at all is not dominant, and exactly half is not enough.

Counting by a full pass is too slow for the intended solution. Locate the first position of x with a binary search, then look at the position that is nums.length / 2 (integer division) further along and test whether it still holds x. Aim for O(log n) time and O(1) extra space.

Example 1

Input:
nums = [1,2,2,2,3], x = 2
Output:
true
Explanation:

The value 2 appears 3 times out of 5, which is more than half.

Example 2

Input:
nums = [4,4,5,5], x = 4
Output:
false
Explanation:

The value 4 appears exactly 2 times out of 4, which is not more than half.

Example 3

Input:
nums = [7], x = 7
Output:
true
Explanation:

A single reading equal to x is trivially a strict majority.

Constraints

1 ≤ nums.length ≤ 1000

-109 ≤ nums[i], x ≤ 109

nums is sorted in non-decreasing order

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(log n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…