Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Optimize for Time and Space

HardCoding00:00
Practice interviewer
In session
5 left
00:00

Your question is Optimize for Time and Space. Take a moment with it on the right.

Talk me through your thinking if you like. When you're confident, submit your answer and I'll grade it like a real screen (7/10 or better passes).

You need to log in / sign up to chat or submit.

Problem

Verily's wearable sensor pipeline needs to find, for each patient, every pair of heart-rate readings taken within 5 minutes of each other where the readings differ by more than 30 bpm, since that pattern can indicate a sensor fault worth flagging for review. Here's the function a colleague wrote for a single patient's sorted readings.

import java.util.ArrayList;
import java.util.List;

public class SensorFaultDetector {

    public List<int[]> findSuspiciousPairs(List<Reading> readings) {
        List<int[]> flagged = new ArrayList<>();
        for (int i = 0; i < readings.size(); i++) {
            for (int j = 0; j < readings.size(); j++) {
                Reading a = readings.get(i);
                Reading b = readings.get(j);
                long minutesApart = Math.abs(a.timestampMillis - b.timestampMillis) / 60000;
                int bpmDiff = Math.abs(a.bpm - b.bpm);
                if (minutesApart <= 5 && bpmDiff > 30) {
                    flagged.add(new int[]{i, j});
                }
            }
        }
        return flagged;
    }

    public static class Reading {
        long timestampMillis;
        int bpm;

        public Reading(long timestampMillis, int bpm) {
            this.timestampMillis = timestampMillis;
            this.bpm = bpm;
        }
    }
}

readings is already sorted by timestamp in ascending order. Optimize this function for time and space complexity, and explain the complexity of your version compared to the original, given that patients can have tens of thousands of readings from a multi-day wearable session.