Leap Year
Problem link : Leap Year
Problem: Check if a Year is a Leap Year
Problem Statement
You are given an integer n representing a year. Your task is to determine whether the year is a leap year or not.
Definition of a Leap Year:
A year is a leap year if:
-
It is divisible by 4, and
-
It is not divisible by 100, unless it is also divisible by 400
Examples
Example 1:
Input: n = 4
Output: true
Explanation: 4 is divisible by 4 and not divisible by 100, so it's a leap year.
Example 2:
Input: n = 2021
Output: false
Explanation: 2021 is not divisible by 4, so it's not a leap year.
Intuition
To check whether a given year is a leap year, follow the leap year rules. These are well-known rules used in the Gregorian calendar.
-
If a year is divisible by 400, it is a leap year.
-
If a year is divisible by 100 but not by 400, it is not a leap year.
-
If a year is divisible by 4 but not by 100, it is a leap year.
-
Otherwise, it is not a leap year.
Approach
Use a simple conditional check using the above rules:
(N % 4 == 0 && N % 100 != 0) || (N % 400 == 0)
This condition directly implements the leap year logic.
Code (Java)
// User function Template for Java
class Solution {
static boolean isLeap(int N) {
return (N % 4 == 0 && N % 100 != 0) || (N % 400 == 0);
}
}
Time and Space Complexity
-
Time Complexity: O(1)
Only constant-time arithmetic and logical operations are performed. -
Space Complexity: O(1)
No additional memory is used.
Dry Run
Input: N = 2000
-
2000%4=0 ✅
-
2000%100=0 ✅
-
2000%400=0 ✅
-
So:
(true && false) || true = true
Output: true
Input: N = 1900
-
1900%4=0 ✅
-
1900%100=0✅
-
1900%400=300 ❌
-
So:
(true && false) || false = false
Output: false
Input: N = 2024
-
2024%4=0 ✅
-
2024%100=24 ❌
-
So:
true && true = true
Output: true
Conclusion
This problem is a direct application of well-established rules to determine leap years. It can be solved efficiently in constant time using basic conditional checks.