We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Date Range Generator

Number: 2799

Difficulty: Medium

Paid? Yes

Companies: N/A


Problem Description

Given a start date, an end date, and a positive integer step, design a generator that yields dates (as strings formatted in YYYY-MM-DD) from the start date to the end date inclusive. Each subsequent date is obtained by adding the given number of days (step) to the previous date.


Key Insights

  • Convert the input date strings to a date object to allow arithmetic.
  • Use a loop to increment the date by "step" days until the current date exceeds the end date.
  • Format each generated date into the required "YYYY-MM-DD" string format.
  • For languages without built-in generators, return a collection (like an array or list) of date strings.
  • Use standard libraries for date manipulation to avoid manual date calculations.

Space and Time Complexity

Time Complexity: O(n) where n is the number of generated dates (roughly (end - start)/step + 1).
Space Complexity: O(1) for a generator solution, or O(n) if storing all dates in a collection.


Solution

The solution leverages date manipulation utilities available in most programming languages. We first parse the start and end dates from string format into date objects. Then, using a loop, we yield or collect each date after formatting it into the "YYYY-MM-DD" string format. We increment the current date by the given step (in days) and check if it is within the specified range. This simple iterative process allows us to generate the requested range while keeping the code efficient and easy to understand.


Code Solutions

from datetime import datetime, timedelta

def dateRangeGenerator(start, end, step):
    # Convert start and end date strings into datetime objects.
    current_date = datetime.strptime(start, "%Y-%m-%d")
    end_date = datetime.strptime(end, "%Y-%m-%d")
    
    # Loop until the current_date exceeds end_date.
    while current_date <= end_date:
        # Yield the current date formatted as YYYY-MM-DD.
        yield current_date.strftime("%Y-%m-%d")
        # Increment the current_date by 'step' days.
        current_date += timedelta(days=step)

# Example usage:
# g = dateRangeGenerator("2023-04-01", "2023-04-04", 1)
# for date_str in g:
#     print(date_str)
← Back to All Questions