#1185

Day of the Week

Easy
MathMathematical FormulasModular Arithmetic
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

We can use Zeller's Congruence, a mathematical formula that directly computes the day of the week for any date. This approach is efficient and avoids the need to count days manually.

⚙️

Algorithm

3 steps
  1. 1Step 1: Adjust the month and year for January and February (consider them as months 13 and 14 of the previous year).
  2. 2Step 2: Apply Zeller's Congruence formula: h = (q + (13(m + 1) / 5) + K + (K / 4) + (J / 4) - 2J) % 7.
  3. 3Step 3: Map the result to the corresponding day of the week.
solution.py10 lines
1def dayOfTheWeek(day, month, year):
2    if month < 3:
3        month += 12
4        year -= 1
5    q = day
6    m = month
7    K = year % 100
8    J = year // 100
9    h = (q + (13 * (m + 1)) // 5 + K + (K // 4) + (J // 4) - 2 * J) % 7
10    return ['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'][h]

Complexity note: The time complexity is O(1) because the calculations do not depend on the size of the input; they are performed in constant time.

  • 1Understanding leap years is crucial for accurate calculations.
  • 2Zeller's Congruence is a powerful formula that simplifies the problem.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.