Online store~30 min2s · 256 MBtarget O(rows log(rows cols)) time, O(1) spaceclassic twin: lc-668binary-search-answer
An online store has a rate card for bulk orders. The rows are product sizes numbered 1 to rows, and the columns are quantities numbered 1 to cols. The price in the cell for size i and quantity j is i × j.
Many cells have the same price. Imagine all the prices sorted from the smallest to the largest, with repeats. The store wants the k-th price in that list.
Write kth_in_table(rows, cols, k).
rows × cols cells. The cell in row i and column j, counting from 1, holds the price i * j.Input: rows = 3, cols = 3, k = 5
Output: 3The card is 1 2 3, 2 4 6, 3 6 9, and its sorted prices are 1, 2, 2, 3, 3, 4, 6, 6, 9. The 5th is 3. You do not build the card. Instead, search the price v in the window [lo, hi], and count the cells at most v: row i holds min(cols, v // i) of them.
| Step | lo | hi | mid | cells at most mid | Decision |
|---|---|---|---|---|---|
| 1 | 1 | 9 | 5 | 3 + 2 + 1 = 6 | 6 >= 5, so hi = 5 |
| 2 | 1 | 5 | 3 | 3 + 1 + 1 = 5 | 5 >= 5, so hi = 3 |
| 3 | 1 | 3 | 2 | 2 + 1 + 0 = 3 | 3 < 5, so lo = 3 |
| end | 3 | 3 | the 5th price is 3 |
Input: rows = 1, cols = 1, k = 1
Output: 1A card with one cell has the price 1, which is both the smallest and the largest.
Input: rows = 2, cols = 5, k = 10
Output: 10The prices are 1, 2, 3, 4, 5 and 2, 4, 6, 8, 10. The 10th, the last one, is 10, the top of the range.
1 ≤ rows ≤ 30,000 and 1 ≤ cols ≤ 30,0001 ≤ k ≤ rows × cols, so k is at most 900,000,000The rate card has up to 9 × 10^8 cells. You cannot build it, and you cannot sort it. But you can count the cells at most a value v by looking at each row once, which takes rows steps. A binary search over v, up to 9 × 10^8, needs about 30 counts, so about 10^6 steps.