Date Range Generator Problem
#2777
Description
LeetCode Problem 2777.
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.
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"]
Explanation:
const g = dateRangeGenerator(start, end, step);
g.next().value // '2023-04-01'
g.next().value // '2023-04-02'
g.next().value // '2023-04-03'
g.next().value // '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"]
Explanation:
const g = dateRangeGenerator(start, end, step);
g.next().value // '2023-04-10'
g.next().value // '2023-04-13'
g.next().value // '2023-04-16'
g.next().value // '2023-04-19'
Example 3:
Input: start = "2023-04-10", end = "2023-04-10", step = 1
Output: ["2023-04-10"]
Explanation:
const g = dateRangeGenerator(start, end, step);
g.next().value // '2023-04-10'
Constraints:
new Date(start) <= new Date(end)startandenddates are in the string formatYYYY-MM-DD0 <= The difference in days between the start date and the end date <= 15001 <= step <= 1000
Solution
Approach: Generator with UTC date arithmetic
A generator is the natural fit: it hands out one date at a time and never builds the whole list (up to 1501 dates here, but the idea is the point).
- Parse
startandendintoDateobjects. AYYYY-MM-DDstring is parsed as UTC midnight, so every later step should use the UTC methods too. Mixing in local-timesetDatecan slip a day across a daylight-saving change. - While the current date is not after
end, yield its ISO string cut to the first 10 characters (YYYY-MM-DD), then move forward withsetUTCDate(getUTCDate() + step).Datehandles month and year rollover for us. - The comparison
current <= lastworks onDateobjects because they convert to timestamps.
The tricky case is start == end, which must yield exactly one date; the loop condition handles it.
Complexity: Time O(n) for n yielded dates, extra space O(1).
/**
* @param {string} start
* @param {string} end
* @param {number} step
* @return {Generator<string>}
*/
var dateRangeGenerator = function* (start, end, step) {
const current = new Date(start);
const last = new Date(end);
while (current <= last) {
yield current.toISOString().slice(0, 10);
current.setUTCDate(current.getUTCDate() + step);
}
};