#1175

Prime Arrangements

Easy
MathMathematical counting principlesFactorial calculations
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

Instead of generating permutations, we can directly calculate the number of valid arrangements by counting primes and composites. The number of valid arrangements is the product of the factorials of the counts of primes and composites.

⚙️

Algorithm

4 steps
  1. 1Step 1: Count the number of prime numbers up to n.
  2. 2Step 2: Count the number of composite numbers up to n.
  3. 3Step 3: Calculate the factorial of the count of primes and the count of composites.
  4. 4Step 4: Return the product of these factorials modulo 10^9 + 7.
solution.py10 lines
1def factorial(x):
2    result = 1
3    for i in range(2, x + 1):
4        result = (result * i) % (10**9 + 7)
5    return result
6
7def prime_arrangements(n):
8    primes_count = sum(1 for i in range(2, n + 1) if is_prime(i))
9    composites_count = n - primes_count
10    return (factorial(primes_count) * factorial(composites_count)) % (10**9 + 7)

Complexity note: The time complexity is O(n) because we only need to count primes and composites, and calculate their factorials, which is efficient compared to generating permutations.

  • 1Understanding prime numbers and their properties is crucial for this problem.
  • 2The factorial function grows rapidly, so we must use modulo to prevent overflow.

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