1498. Kth Signed Product

Hard7.5 points estimatedBinary SearchTwo PointersArray

Two price lists a and b are each sorted in non-decreasing order and may contain negative numbers and zeros. Consider the n * m products a[i] * b[j] over every pair (i, j), counting equal products separately.

Return the k-th smallest of these products (1-based, with multiplicity) as a long. Binary search the product value V between -10^10 and 10^10, and count the pairs whose product is at most V with a sign-aware two-pointer sweep; compare products directly and never divide or floor negative numbers. The answer is the smallest V whose count is at least k. Target O((n + m) log(range)) time and O(1) extra space.

Example 1

Input:
a = [-2,0,3], b = [-1,4], k = 3
Output:
0
Explanation:

The products sorted are -8, -3, 0, 0, 2, 12, and the third smallest is 0.

Example 2

Input:
a = [2,3], b = [4,5], k = 4
Output:
15
Explanation:

The products sorted are 8, 10, 12, 15, so the fourth smallest is 15.

Example 3

Input:
a = [-5,-3], b = [-4,-2], k = 1
Output:
6
Explanation:

The products are 20, 10, 12, 6, and the smallest is 6.

Constraints

1 ≤ n, m ≤ 5*104; -105 ≤ a[i], b[j] ≤ 105; both sorted non-decreasing; 1 ≤ k ≤ n*m

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 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms

Expected complexity

Time
O((n + m) log(range))
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…