← 返回 instacart 的题目列表Onsite Coding: File Matrix Lookup
类型:qbank
Given a file containing one matrix, return the value at a requested row and column. Follow-up: the file contains multiple matrices, each preceded by a key; return a map from key to that matrix's value at the requested coordinates.
Requirements
Input: file path or file-like object, target row, target col.
Basic version: file contains one rectangular matrix. Return matrix[row][col].
Follow-up: file contains multiple matrices; each matrix has a key/header before its rows. Return {key -> value_at(row, col)} for every matrix that contains the coordinate.
Clarify indexing: 0-based vs 1-based row/col.
Clarify delimiter: comma-separated, whitespace-separated, or fixed-width.
Clarify behavior when a matrix is smaller than the requested row/column.
Example:
A
1 2 3
4 5 6
B
7 8
9 10
row=1, col=1 -> {"A": 5, "B": 10}
Notes
The simple solution is to read the whole file into memory, parse matrices, and index into each matrix. That is acceptable for small files but expect a follow-up about streaming.
Streaming version: scan line by line, track current matrix key, current row index inside the matrix, and only parse the target row for each matrix. This reduces memory from O(file_size) to O(max_line_length + number_of_matrices).
If rows are fixed width and row lengths are known, a file pointer / seek solution can jump directly to a row. Otherwise, line-by-line streaming is the practical optimization.
Be explicit about malformed input: blank lines separate matrices, inconsistent row length either errors or skips the matrix, and missing target column returns null for that key.
Common failure mode: over-optimizing before the basic parser works. Ship the simple parser, then explain the streaming memory optimization.
Preparation
Practice parsing text files with both readlines() and streaming iteration.
Write a version that never stores a full matrix: keep only the target row for each key.
Prepare tests for missing row, missing column, multiple matrices, and trailing blank lines.