1348. Weighted Middle Value

Medium3.5 points estimatedQuickselectArrayPrefix Sum

A survey records answers as numbers in the array nums, and respondent i carries an importance weight of weights[i]. The weighted middle value is the smallest value v present in nums such that the total weight of all entries with value at most v is at least half of the grand total weight. In integer form, the test is 2 * (weight of entries with value <= v) >= total weight.

Return that value v. The sums can exceed 32 bits in general, so use 64-bit arithmetic. Sorting and scanning prefix weights costs O(n log n). The intended solution is a quickselect that partitions around a pivot and recurses only into the side holding the half-weight boundary, for expected O(n) time and O(n) space.

Example 1

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

The total weight is 3. The value 1 covers weight 1 (not enough), the value 2 covers weight 2 and 2 * 2 >= 3.

Example 2

Input:
nums = [10,20,30], weights = [1,1,5]
Output:
30
Explanation:

The total weight is 7. The values 10 and 20 cover only 1 and 2 units of weight, while 30 covers 7, so 30 is the first value to reach half.

Example 3

Input:
nums = [4,-2,9], weights = [2,2,2]
Output:
4
Explanation:

The total weight is 6. The value -2 covers 2, and the value 4 covers 4 with 2 * 4 >= 6.

Constraints

  • 1 ≤ n ≤ 105, where n is the length of nums
  • weights.length == n
  • -109 ≤ nums[i] ≤ 109
  • 1 ≤ weights[i] ≤ 104

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 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(n)

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…