Leetcode 1175. Prime Arrangements
Given an integer n
, you need to return the number of prime arrangements. You can rearrange the first n
positive integers to make nums such that the number of prime numbers present in the first k
positions of the rearranged array is equal to k
. Since the answer may be large, return it modulo 10^9 + 7
.
n
?
1 <= n <= 100
10^9 + 7
?
10^9 + 7
.n
. We can use the Sieve of Eratosthenes to count the primes efficiently.n
.10^9 + 7
.import java.util.*;
public class PrimeArrangements {
private static final int MOD = 1_000_000_007;
public int numPrimeArrangements(int n) {
int primeCount = countPrimes(n);
// Calculate factorial of primeCount and nonPrimeCount
long primeFactorial = factorial(primeCount);
long nonPrimeFactorial = factorial(n - primeCount);
// Return the product modulo 10^9 + 7
return (int) ((primeFactorial * nonPrimeFactorial) % MOD);
}
private int countPrimes(int n) {
boolean[] isPrime = new boolean[n + 1];
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false; // 0 and 1 are not primes
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
int count = 0;
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
count++;
}
}
return count;
}
private long factorial(int num) {
long result = 1;
for (int i = 2; i <= num; i++) {
result = (result * i) % MOD;
}
return result;
}
public static void main(String[] args) {
PrimeArrangements sol = new PrimeArrangements();
System.out.println(sol.numPrimeArrangements(5)); // Example output: 12
System.out.println(sol.numPrimeArrangements(100)); // Example output
}
}
O(n log log n)
for counting the primes.O(n)
for computing the factorials.O(n log log n)
due to the sieve.This approach ensures that we handle the constraints efficiently and return the result within permissible computational limits.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?