Search~20 min2s · 256 MBtarget O(q (m + n)) time, O(1) spaceclassic twin: lc-240binary-search
A search engine keeps a table of relevance scores. Each row is a group of results, and each column is a freshness band. A score never falls as you move right along a row, and it never falls as you move down a column.
The rows overlap: the first score of a row can be smaller than the last score of the row above. Analysts check many scores. For each one, they want to know whether it appears in the table.
Write scores_present(scores, queries).
scores[r][c] is the score in row r and column c. Every row, from left to right, never falls. Every column, from top to bottom, never falls.Input: scores = [[2, 5, 9, 14], [3, 6, 10, 15], [7, 8, 12, 18], [11, 13, 16, 20]], queries = [12, 7, 17, 1, 20, 4]
Output: [1, 1, 0, 0, 1, 0]Take the query 17. Start in the top-right corner. If the entry is below the query, nothing to its left can reach it, so you move down. If the entry is above the query, nothing below it can be as small, so you move left.
| Step | Row | Column | Entry | Decision |
|---|---|---|---|---|
| 1 | 0 | 3 | 14 | below 17, so move down |
| 2 | 1 | 3 | 15 | below 17, so move down |
| 3 | 2 | 3 | 18 | above 17, so move left |
| 4 | 2 | 2 | 12 | below 17, so move down |
| 5 | 3 | 2 | 16 | below 17, so move down |
| end | 4 | 2 | the row is outside the table, so 17 is missing |
The queries 12, 7 and 20 are in the table. The queries 1 and 4 are not.
Input: scores = [[5]], queries = [5, 4, 6]
Output: [1, 0, 0]A table with one cell holds one score.
Input: scores = [[1, 1], [1, 3]], queries = [1, 2, 3, 0]
Output: [1, 0, 1, 0]Equal scores are allowed. The query 2 falls between 1 and 3 and is missing.
scores has m rows and n columns, with 1 ≤ m, n ≤ 500, so up to 250,000 scores0 ≤ scores[r][c], queries[j] ≤ 1,000,000,0000 ≤ queries.length ≤ 2,000Scanning the whole table for every query costs about 250,000 steps, which is 5 × 10^8 for 2,000 queries. A walk from a corner removes a row or a column at every step. So one query takes at most m + n - 1 steps, which is under 1,000. That is about 2 × 10^6 steps in all.