Search~20 min2s · 256 MBtarget O(n + q) time, O(n) spacecomplexity · recursion
A search service looks up a query code in a list of codes with a recursive function. The function find(i) returns i when codes[i] equals the query, returns -1 when i reaches the end of the list, and otherwise calls find(i + 1).
Every call that is still waiting keeps a frame on the stack. The team wants the peak stack memory over a day of lookups, which depends on the worst lookup and not on the typical one.
Write peak_stack_bytes(codes, queries, frame_bytes).
find(0) runs as described, and the lookup stops at the first position whose code equals the query.find(i) is one frame. A lookup keeps all its frames alive until the last call returns, and the call that reaches the end of the list is a frame too.frame_bytes bytes. Return the largest number of stack bytes any single lookup needs.Input: codes = [40, 12, 7, 33, 19], queries = [12, 19, 99, 40], frame_bytes = 64
Output: 384A hit at position p keeps p + 1 frames, and a miss keeps one more than the length of the list.
| Query | Where it sits | Frames alive | Bytes |
|---|---|---|---|
| 12 | position 1 | 2 | 128 |
| 19 | position 4 | 5 | 320 |
| 99 | not listed | 6 | 384 |
| 40 | position 0 | 1 | 64 |
The deepest lookup is the miss, so the peak is 384 bytes.
Input: codes = [], queries = [5], frame_bytes = 100
Output: 100With no codes, find(0) already reaches the end and returns -1. That is 1 frame, 100 bytes.
Input: codes = [3, 4], queries = [], frame_bytes = 50
Output: 0With no queries, no lookup runs: 0.
0 ≤ codes.length ≤ 100,000 (codes)1 ≤ codes[i] ≤ 1,000,000 (code values)0 ≤ queries.length ≤ 100,000 (lookups)1 ≤ queries[j] ≤ 1,000,000 (searched codes)16 ≤ frame_bytes ≤ 1,000 (bytes of one frame)Running every lookup costs up to 10^5 × 10^5 = 10^10 calls. The peak depends only on the deepest lookup, so find that one without running the others. The bytes can be large, so use 64-bit integers.