Ride-hailing app~15 min2s · 256 MBtarget O(q) time, O(q) spaceclassic twin: lc-1185number-theory
You work on a ride booking app. Riders pick a travel date, and the app shows the day of the week next to it, such as Monday or Friday. The app uses the standard calendar. A year is a leap year when 4 divides it, except when 100 divides it and 400 does not.
Your team lead asks: "What is the weekday of each date in this list?" A request can hold 100,000 dates, in years from 1 to 9999.
Write weekdays(dates).
dates[i] = [day, month, year] is a valid date. Months count from 1 to 12.Input: dates = [[15, 8, 1947], [29, 2, 2000], [31, 12, 9999]]
Output: [5, 2, 5]Count the days from 1 January of year 1 to the date, divide by 7, and use the remainder. The first date, 15 August 1947, is a Friday.
| Date | Days before it | Remainder | Weekday |
|---|---|---|---|
| 15 August 1947 | 710987 | 4 | Friday |
The other dates give Tuesday and Friday.
Input: dates = [[1, 1, 2024]]
Output: [1]1 January 2024 was a Monday.
Input: dates = [[28, 2, 1900], [1, 3, 1900]]
Output: [3, 4]1900 is not a leap year, so the day after 28 February is 1 March, and the weekday moves on by one.
1 ≤ len(dates) ≤ 100,000[day, month, year], with 1 ≤ year ≤ 9999, and the date existsCounting the days one by one costs up to 3,652,058 steps for one date. A year-by-year loop costs about 9,999 steps for each date, about a billion for 100,000 dates. A formula that jumps over whole years and months takes a few steps for each date.