Code RoomImpute readings with device mean
MediumPrep Room Coding #5135

Impute readings with device mean

CodingAlgorithms & data structuresMid–Senior~11 min

Given `readings` with columns `device`, `ts` and `reading`, replace each missing `reading` with the mean of that device other readings. A device with no readings at all keeps null. Return `device`, `ts` and `reading`, sorted by `device` ascending and then `ts` ascending.

Implement
fill_with_device_mean(readings: dataframe) → dataframe
Examples
in[{"__df__":[{"ts":"2024-05-01","device":"a1","reading":20.5},{"ts":"2024-05-02","device":"a1","reading":null},{"ts":"2024-05-03","device":"a1","reading":22.5},{"ts":"2024-05-01","device":"b2","reading":null},{"ts":"2024-05-02","device":"b2","reading":31},{"ts":"2024-05-03","device":"b2","reading":33}]}]out[{"ts":"2024-05-01","device":"a1","reading":20.5},{"ts":"2024-05-02","device":"a1","reading":21.5},{"ts":"2024-05-03","device":"a1","reading":22.5},{"ts":"2024-05-01","device":"b2","reading":32},{"ts":"2024-05-02","device":"b2","reading":31},{"ts":"2024-05-03","device":"b2","reading":33}]
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.

0:00 of about 11 min
InputExpectedGot
[{"__df__":[{"ts":"2024-05-01","device":"a1","reading":20.5},{"ts":"2024-05-02","device":"a1","reading":null},{"ts":"2024-05-03","device":"a1","reading":22.5},{"ts":"2024-05-01","device":"b2","reading":null},{"ts":"2024-05-02","device":"b2","reading":31},{"ts":"2024-05-03","device":"b2","reading":33}]}][{"ts":"2024-05-01","device":"a1","reading":20.5},{"ts":"2024-05-02","device":"a1","reading":21.5},{"ts":"2024-05-03","device":"a1","reading":22.5},{"ts":"2024-05-01","device":"b2","reading":32},{"ts":"2024-05-02","device":"b2","reading":31},{"ts":"2024-05-03","device":"b2","reading":33}]not run yetsample