Sum Health Samples Within a Time Range Stored in a BST

Last updated: November 29, 2026

Quick Overview

Health samples are stored in a binary search tree keyed by timestamp, each node holding a step count. Return the total steps for all samples with timestamps in [lo, hi], visiting as few nodes as possible.

Apple
Coding & Algorithms
Software Engineer
Apple
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Easy

0

0

0 solved


Health samples are stored in a binary search tree keyed by timestamp, each node holding a step count. Return the total steps for all samples with timestamps in [lo, hi], visiting as few nodes as possible.

A screen question that checks whether a candidate actually uses the BST ordering instead of traversing everything. Apple interviewers often wrap it in HealthKit language and then ask about balancing and range indexes.

What the Interviewer Expects
  • Prune left subtrees when the key is below lo and right subtrees when above hi
  • Use an iterative stack to avoid recursion limits
  • Make the range inclusive on both ends
  • Explain O(h + k) behavior
  • Discuss what happens if the tree is unbalanced
Key Topics to Cover
BST
range queries
tree traversal
pruning
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Answer many range queries fast by storing subtree sums in each node.
  • Samples are inserted constantly; how do you keep the tree balanced?
  • How would HealthKit store this on disk instead of in memory?
  • Return the samples in order, not just the sum.
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: BST root of Sample(ts, steps, left, right) and ints lo <= hi. Output: sum of steps where lo <= ts <= hi. Empty tree gives 0. Timestamps are unique....

High-Level Design

Walk the tree with an explicit stack. At a node, if ts < lo, every node in the left subtree is also too small, so only the right child can contain answers. If ts > hi, only the left child can. Oth...


Submit Your Answer
Markdown supported