Prime Arrangements — LeetCode 1175 Python Solution

EasyMath
Problem
#1175
Reading time
3 min

The problem

Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.) (Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.) Since the answer may be large, return the answer modulo 10^9 + 7.

Example

Input
n = 5
Output
12
Explanation
For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.

Python solution

Python
class Solution:
    def numPrimeArrangements(self, n: int) -> int:
        def count(n):
            cnt = 0
            primes = [True] * (n + 1)
            for i in range(2, n + 1):
                if primes[i]:
                    cnt += 1
                    for j in range(i + i, n + 1, i):
                        primes[j] = False
            return cnt

        cnt = count(n)
        ans = factorial(cnt) * factorial(n - cnt)
        return ans % (10**9 + 7)

Complexity

MeasureComplexity
TimeO(n \times \log \log n)
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1175. Prime Arrangements is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1175. Prime Arrangements?
LeetCode 1175. Prime Arrangements is rated Easy on LeetCode.
What is the time complexity of LeetCode 1175. Prime Arrangements?
The Python solution on this page runs in O(n \times \log \log n).
What is the space complexity of LeetCode 1175. Prime Arrangements?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1175. Prime Arrangements cover?
LeetCode 1175. Prime Arrangements is tagged Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview