Find Strictly Decreasing Forecast Windows for Equatorial Cities
VersemedicalSoftware Engineer · OnsiteLast updated
This problem tests the ability to handle API integration, data stream processing, and sliding window logic while managing error handling and rate-limiting constraints.
Problem Description
Build a service function get_decreasing_windows(city_id) that identifies all 8-hour intervals where the temperature forecast is strictly decreasing.
Requirements
- Data Access: Query a PostgreSQL database to retrieve the latitude/longitude for a given
city_id. Only proceed if the city is equatorial (latitude between -5 and 5 degrees). - Data Acquisition: Fetch the next 72 hours of hourly forecast data from an external Weather API. The API returns a list of objects:
{'timestamp': 'YYYY-MM-DDTHH:MM:SSZ', 'temp': float}. - Resilience: The API is unstable. Implement a retry mechanism with exponential backoff for 5xx errors. If the API returns a 429 (Too Many Requests), respect the
Retry-Afterheader. - Logic: Identify all 8-hour sliding windows (consecutive timestamps) where
temp[i] > temp[i+1] > ... > temp[i+7]. - Validation: Ensure data continuity; if an hour is missing in the API response, that window cannot be considered valid.
Function Signature
def get_decreasing_windows(city_id: int) -> List[Tuple[str, str]]:
# Returns a list of (start_timestamp, end_timestamp) tuples
Example
Input sequence (temps): [30, 29, 28, 27, 26, 25, 24, 23, 22, 24]
- Window 1 (indices 0-7):
[30, 29, 28, 27, 26, 25, 24, 23](Strictly decreasing: Yes) - Window 2 (indices 1-8):
[29, 28, 27, 26, 25, 24, 23, 22](Strictly decreasing: Yes) - Window 3 (indices 2-9):
[28, 27, 26, 25, 24, 23, 22, 24](Strictly decreasing: No) Result:[('2023-10-01T00:00:00Z', '2023-10-01T07:00:00Z'), ('2023-10-01T01:00:00Z', '2023-10-01T08:00:00Z')]
Edge Cases
- Missing data points (gaps in time).
- City outside equatorial range.
- Fewer than 8 hours of total data returned.
Hints
Hint 1
Use a helper function to validate the strictly decreasing condition using a simple loop or a deque to maintain a sliding window.
Hint 2
Implement an exponential backoff decorator or a simple loop that checks the response status code before parsing the JSON body.
Hint 3
To handle gaps, parse the ISO timestamps into Python datetime objects and compare consecutive timestamps to ensure the delta is exactly one hour.
Follow-up questions
- How would you modify this solution if the city list was massive and you needed to perform this calculation for all equatorial cities every hour?
- What strategies would you implement to cache the weather results to minimize API costs and stay within rate limits?
- How would you mock the external Weather API to write unit tests for the retry logic and edge cases like missing timestamps?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.