A monitoring service stores response times per server: each row of a matrix holds one server's measurements, sorted ascending. The dashboard asks for the median response time across all servers, and other percentiles, many times a second. Rows can have different lengths.
Write two functions. rows is an array of rows, and every row is an array of integers sorted in non-decreasing order.
kthSmallestInRows(rows, k) returns the k-th smallest value among all cells, counting from k = 1. Duplicates count separately: in [[1, 1, 2]] the second smallest is 1.
rowSortedMedian(rows) returns the median of all cells: the middle value when the total count is odd, and the average of the two middle values when it is even.
Rules:
Values are integers between -1,000,000,000 and 1,000,000,000. Rows may be empty, but the matrix must have at least one cell in total.
Throw a TypeError when rows is not an array of arrays, the matrix has no cells, or k is not an integer from 1 to the total number of cells. The values themselves are trusted: checking every cell would cost as much as the slow solution.
The tests build a 1,000 × 1,000 matrix and ask for 100 different ranks. Flattening and sorting a million cells on every call is far too slow; each call should cost about rows × log(columns) × log(value range) steps.
const m = [ [1, 3, 5], [2, 6, 9], [3, 6, 9],];rowSortedMedian(m); // 5: the sorted cells are 1 2 3 3 5 6 6 9 9kthSmallestInRows(m, 1); // 1kthSmallestInRows(m, 4); // 3: the second 3rowSortedMedian([[1, 10], [2, 3, 4], []]); // 3rowSortedMedian([[4, 7], [1, 8]]); // 5.5: the average of 4 and 7
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
7
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.