Code Room
CodingHardcod-g1083
Subject Query cost based optimizerLevel Senior–Staff~30 minCommon in Databases & SQL interviewsIndustries Software development, Technology

Question

A cost-based optimizer must pick between two access paths for a selection. You are given table_rows (int row count), a 'selectivity' float in [0,1] (fraction of rows matching the predicate), and a 'has_index' bool. The full scan costs table_rows (one unit per row read). The index path, available only if has_index is true, costs 3 (index descent) plus 5 * (matched rows), where matched rows = round(table_rows * selectivity) using Python's round. Return the string 'index' if the index path exists and its cost is strictly less than the scan cost, otherwise 'scan'. Also return the chosen cost. Return [choice, cost].

Implement
choose_access_path(table_rows: int, selectivity: float, has_index: bool) → list
Examples
in[1000,0.01,true]out["index",53]
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

Vibe coding: describe the solution in plain language (or narrate it) and the coach grades your approach. Generating runnable code from your description is coming next.

Run or narrate your approach, then ask the coach.