The Diet Plan Performance interview question asks you to evaluate a person's diet over a period of time. You are given an array of calories consumed each day, a window of days represented by an integer , and two thresholds: lower and upper. For every consecutive period of days, you calculate the total calories consumed. If the total is less than lower, the person loses 1 point. If the total is greater than upper, the person gains 1 point. Otherwise, the points remain unchanged. The goal is to find the total points accumulated by the end of the diet plan.
Amazon frequently uses this coding problem to test a candidate's understanding of basic data processing and optimization. It specifically targets the Sliding Window interview pattern. While a beginner might recalculate the sum for every window from scratch (), an experienced engineer knows how to update the sum in constant time () as the window slides. This demonstrates efficiency and attention to performance, which are critical traits for software engineers working on large-scale systems.
The primary pattern is the Sliding Window. Instead of summing elements for every starting position, you maintain a running total. For the first days, you calculate the sum normally. For each subsequent day, you add the calories of the new day entering the window and subtract the calories of the day that just left. This ensures that each window's evaluation takes time after an initial setup, leading to an overall time complexity.
Suppose calories = [1, 2, 3, 4, 5], k = 2, lower = 3, upper = 6.
Master the Sliding Window interview pattern. It is a fundamental technique for problems involving contiguous subarrays or substrings. When you see "fixed-size window" or "consecutive elements," your first thought should be: "Can I update the result by just looking at the elements entering and leaving the window?"