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
.
Examples
Example 1: Input: start = “2023-04-01”, end = “2023-04-04”, step = 1 Output: [“2023-04-01”,“2023-04-02”,“2023-04-03”,“2023-04-04”]
Example 2: Input: start = “2023-04-10”, end = “2023-04-20”, step = 3 Output: [“2023-04-10”,“2023-04-13”,“2023-04-16”,“2023-04-19”]
Example 3: Input: start = “2023-04-10”, end = “2023-04-10”, step = 1 Output: [“2023-04-10”]
Constraints:
new Date(start) <= new Date(end)
start
andend
dates are in the string formatYYYY-MM-DD
0 <= The difference in days between the start date and the end date <= 1500
1 <= step <= 1000
Solution
Method 1 – Date Increment Generator 1
Intuition
We can generate the required date range by starting from the start
date and incrementing by step
days each time, yielding each date until we pass the end
date. This works because date arithmetic is well-defined and the constraints are small.
Approach
- Parse the
start
andend
strings into date objects. - Use a loop to yield the current date in
YYYY-MM-DD
format. - Increment the current date by
step
days each iteration. - Stop when the current date exceeds the
end
date. - Handle edge cases where
start == end
orstep
is large.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
where n is the number of yielded dates, because we increment and yield once per output date. - 🧺 Space complexity:
O(1)
, as only a few variables are used regardless of the range size.