algoadvance

Leetcode 2413. Smallest Even Multiple

Problem Statement

Given a positive integer n, return the smallest positive integer that is a multiple of both 2 and n.

Example:

Input: n = 5
Output: 10
Explanation: The smallest multiple of both 2 and 5 is 10.
Input: n = 6
Output: 6
Explanation: The smallest multiple of both 2 and 6 is 6 since 6 is already even.

Clarifying Questions

  1. What is the range of the input value n?
    • The problem states that n is a positive integer. To ensure thoroughness, checking the constraints in the problem description would be ideal.
  2. Is there any specific performance requirement or constraints to consider?
    • Given the nature of the problem, it seems straightforward without stringent performance constraints, but we aim to write an efficient solution.

Strategy

To find the smallest positive integer that is a multiple of both 2 and n, we can use the following observations:

  1. The smallest positive multiple of 2 and any integer n is simply 2 * n if n is odd.
  2. If n is even, n itself is already a multiple of 2.

Thus, the smallest positive integer that is a multiple of both 2 and n can be found using:

This leads to a simple conditional check in our implementation.

Code

public class SmallestEvenMultiple {
    public int smallestEvenMultiple(int n) {
        if (n % 2 == 0) {
            return n;
        } else {
            return 2 * n;
        }
    }

    public static void main(String[] args) {
        SmallestEvenMultiple sem = new SmallestEvenMultiple();
        System.out.println(sem.smallestEvenMultiple(5));  // Output: 10
        System.out.println(sem.smallestEvenMultiple(6));  // Output: 6
    }
}

Time Complexity

The time complexity of this solution is O(1) because:

Summary

This solution leverages the properties of even and odd numbers to quickly determine the smallest even multiple of any given integer n. It runs in constant time and meets the problem’s requirements with minimal computational overhead.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI