Watch 10 video solutions for Next Day, a easy level problem. This walkthrough by NeetCode has 2,927,660 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
Write code that enhances all date objects such that you can call the date.nextDay() method on any date object and it will return the next day in the format YYYY-MM-DD as a string.
Example 1:
Input: date = "2014-06-20"
Output: "2014-06-21"
Explanation:
const date = new Date("2014-06-20");
date.nextDay(); // "2014-06-21"
Example 2:
Input: date = "2017-10-31" Output: "2017-11-01" Explanation: The day after 2017-10-31 is 2017-11-01.
Constraints:
new Date(date) is a valid date objectProblem Overview: Given a date in YYYY-MM-DD format, compute the calendar date for the next day. The solution must correctly handle month boundaries, leap years, and year transitions such as 2023-12-31 → 2024-01-01.
Approach 1: Built-in Date Handling (O(1) time, O(1) space)
The simplest way is to rely on the language’s built-in date utilities. Parse the input string into a Date object, add one day using a timestamp or date method, then format the result back to YYYY-MM-DD. Internally the runtime already handles leap years, varying month lengths, and year rollovers. This approach is concise and reliable for production code. The key operations are parsing the string, incrementing the day value, and formatting the output string. While the underlying library performs more work internally, from an algorithmic perspective the operations run in constant time O(1) and use O(1) space.
Approach 2: Manual Calendar Simulation (O(1) time, O(1) space)
This approach parses the year, month, and day integers and manually simulates calendar rules. Maintain an array of days per month and adjust February when the year is a leap year. A leap year occurs when (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0). Increment the day by one, then check if it exceeds the maximum days for that month. If it does, reset the day to 1 and increment the month. If the month becomes 13, reset it to 1 and increment the year. Finally, format the result with leading zeros to maintain the YYYY-MM-DD format. This solution is a straightforward simulation problem using basic math conditions and simple string formatting.
Recommended for interviews: Manual calendar simulation. Interviewers want to see that you understand leap year rules and boundary transitions between days, months, and years. The built-in date approach demonstrates practical engineering, but the simulation approach shows stronger problem-solving ability and control over edge cases.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Built-in Date Handling | O(1) | O(1) | Quick implementation in real-world code where standard libraries are allowed |
| Manual Calendar Simulation | O(1) | O(1) | Preferred in interviews to demonstrate understanding of leap years and date boundaries |