Smallest Even Multiple (LeetCode 2413): Solution and Explanation
Given a positive integer n, return the smallest positive integer divisible by both 2 and n.
Intuition
A number divisible by both 2 and n is a common multiple, and the smallest one is the least common multiple, lcm(2, n).
Picture the number line with a tick on every even number, and hop along it in steps of n. The first hop lands on n. If n is even it sits on a tick and you are done.
If n is odd, the first hop misses. The second hop lands on 2n, which is even by construction, so it is the answer. There is never a need for a third hop.
Approach: Parity check
- If
n % 2 == 0, returnn. - Otherwise return
n * 2.
Step-by-step example
n = 5
- The multiples of 5 are 5, 10, 15, ... and the multiples of 2 are 2, 4, 6, 8, 10, ...
- The first multiple of 5 is 5. 5 % 2 = 1, so it is odd and not a multiple of 2.
- The next multiple is 10 = 2 * 5, which is even.
- Return 10.
Code: Python, Java, C++
1class Solution:
2 def smallestEvenMultiple(self, n: int) -> int:
3 if n % 2 == 0:
4 return n
5 return n * 21class Solution {
2 public int smallestEvenMultiple(int n) {
3 if (n % 2 == 0) {
4 return n;
5 }
6 return n * 2;
7 }
8}1class Solution {
2public:
3 int smallestEvenMultiple(int n) {
4 if (n % 2 == 0) {
5 return n;
6 }
7 return n * 2;
8 }
9};Time and space complexity
O(1)
One modulo check and at most one multiplication.
O(1)
No extra storage.
Other approaches
lcm formula (time O(1), space O(1))
Compute 2 * n / gcd(2, n) with a gcd helper. It generalizes to lcm(a, b) for any pair, at the cost of a gcd call.
Bit trick (time O(1), space O(1))
n << (n & 1) shifts n left by one exactly when n is odd, which doubles it. Same result in one expression, but less readable.
Common mistakes
- Returning 2 * n for every input. For an even n such as 6 that gives 12, but 6 already works.
- Starting the search at 0. The answer must be positive, and 0 is a multiple of everything.
- Overthinking with a loop over candidates. Two cases cover every n.
Frequently asked questions
Why is 2n always a valid answer?
2n is a multiple of n because it is n times 2, and it is a multiple of 2 because it is 2 times n. The question is only whether something smaller works, and that happens exactly when n is even.
How does this relate to lcm?
lcm(a, b) = a * b / gcd(a, b). With a = 2, gcd(2, n) is 2 for even n and 1 for odd n, giving n and 2n.
What does the answer look like for n = 1?
1 is odd, so the answer is 2.