Date Range Generator - Problem

Given a start date start, an end date end, and a positive integer step, return a generator object that yields dates in the range from start to end inclusive.

The value of step indicates the number of days between consecutive yielded values. All yielded dates must be in the string format YYYY-MM-DD.

Note: The generator should yield dates chronologically and include both start and end dates if they fall on valid step intervals.

Input & Output

Example 1 — Basic Weekly Step
$ Input: start = "2023-01-01", end = "2023-01-15", step = 7
Output: ["2023-01-01", "2023-01-08", "2023-01-15"]
💡 Note: Starting from 2023-01-01, add 7 days each time: 2023-01-01 → 2023-01-08 → 2023-01-15. All dates are within range.
Example 2 — Daily Step
$ Input: start = "2023-02-28", end = "2023-03-03", step = 1
Output: ["2023-02-28", "2023-03-01", "2023-03-02", "2023-03-03"]
💡 Note: Step of 1 day across month boundary. February ends on 28th (2023 is not leap year), so next date is March 1st.
Example 3 — Large Step
$ Input: start = "2023-01-01", end = "2023-01-10", step = 15
Output: ["2023-01-01"]
💡 Note: First date is 2023-01-01. Next would be 2023-01-16 which exceeds end date 2023-01-10, so only start date is yielded.

Constraints

  • start and end are valid dates in format YYYY-MM-DD
  • start ≤ end
  • 1 ≤ step ≤ 1000
  • Date range will not exceed 10 years

Visualization

Tap to expand
Date Range Generator INPUT Date Range 2023-01-01 2023-01-15 Parameters: start = "2023-01-01" end = "2023-01-15" step = 7 days 15-day span Jan 01 Jan 15 ALGORITHM STEPS 1 Parse Dates Convert strings to date objects for calculation 2 Initialize Generator Set current = start_date Yield first value 3 Iterate with Step While current <= end: current += step days 4 Yield Formatted Convert back to string Format: YYYY-MM-DD Generator Flow Jan 01 --> Jan 08 --> Jan 15 +7 days each iteration FINAL RESULT Generator Output "2023-01-01" "2023-01-08" "2023-01-15" Output Array: ["2023-01-01", "2023-01-08", OK 3 dates generated "2023-01-15"] Visual Timeline 01 08 15 Key Insight: Using a generator function with yield allows lazy evaluation - dates are computed on-demand, not all at once. This is memory-efficient for large date ranges. The timedelta object handles month/year boundaries automatically, making the step increment robust and reliable. TutorialsPoint - Date Range Generator | Efficient Date Iterator Approach
Asked in
Google 35 Microsoft 28 Amazon 22 Apple 15
34.7K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen