Bank app~20 min2s · 256 MBtarget O(q log(m n)) time, O(1) spaceclassic twin: lc-74binary-search
A bank app shows a customer's statement as pages. Each page is a row of transaction numbers, listed in increasing order. The next page continues where the last one ended, so the first number on a page is larger than every number on the page before it.
Support staff look up many transaction numbers. For each one, they want the page and the position on the page, or a sign that it is not on the statement.
Write find_in_pages(pages, queries).
pages[r][c] is the transaction number in row r, column c. Every row has the same number of columns.[r, c] where it is found, or [-1, -1] when it is missing.Input: pages = [[3, 8, 12, 20], [25, 31, 40, 47], [52, 60, 71, 90]], queries = [31, 3, 90, 50, 100, 20]
Output: [[1, 1], [0, 0], [2, 3], [-1, -1], [-1, -1], [0, 3]]The grid has 12 entries. Think of them as one list, numbered 0 to 11 in reading order. Position p is row p // 4 and column p % 4. Take the query 31.
The window [lo, hi) holds the positions that might be the first entry not below 31.
| Step | lo | hi | mid | row, column | pages entry | Decision |
|---|---|---|---|---|---|---|
| 1 | 0 | 12 | 6 | 1, 2 | 40 | not below 31, so hi = 6 |
| 2 | 0 | 6 | 3 | 0, 3 | 20 | 20 < 31, so lo = 4 |
| 3 | 4 | 6 | 5 | 1, 1 | 31 | not below 31, so hi = 5 |
| 4 | 4 | 5 | 4 | 1, 0 | 25 | 25 < 31, so lo = 5 |
| end | 5 | 5 | 1, 1 | 31 | equal to the query, so the answer is [1, 1] |
The query 3 is at [0, 0], the query 90 at [2, 3] and the query 20 at [0, 3]. The queries 50 and 100 are missing.
Input: pages = [[7]], queries = [7, 6, 8]
Output: [[0, 0], [-1, -1], [-1, -1]]A grid with one entry is a list of one: the query 7 is found, and 6 and 8 are missing.
Input: pages = [[1, 2], [4, 5], [7, 8]], queries = [5, 2, 6, 0]
Output: [[1, 1], [0, 1], [-1, -1], [-1, -1]]This grid has 3 rows and 2 columns, so position p is row p // 2 and column p % 2. The query 5 is at [1, 1], and 2 at [0, 1]. The queries 6 and 0 are missing.
pages is a grid of m rows and n columns, with 1 ≤ m, n ≤ 500, so up to 250,000 entries0 ≤ queries.length ≤ 100,0000 ≤ pages[r][c], queries[j] ≤ 1,000,000,000Scanning the whole grid for every transaction number costs about m × n × q steps, which is 2.5 × 10^10 at 250,000 entries and 100,000 queries. The grid reads as one sorted list of 250,000 entries, so a binary search needs about 18 steps per query.