A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 1175. Prime Arrangements, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are factorial, numPrimeArrangements.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- A set is doing the membership or uniqueness work, which keeps the main loop readable.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 4 ms, faster than 54.69% of C++ online submissions for Prime Arrangements.
02//Memory Usage: 8.4 MB, less than 100.00% of C++ online submissions for Prime Arrangements.
03class Solution {
04public:
05 int modulo = pow(10, 9) + 7;
06
07 set<int> primes = {2};
08
09 long int factorial(int n){
10 long int ans = 1;
11 for(int i = n; i >= 1; i--){
12 ans *= i;
13 ans = ans % modulo;
14 }
15 return ans;
16 }
17
18 int numPrimeArrangements(int n) {
19 for(int i = 3; i <= n; i++){
20 bool isPrime = true;
21 for(int prime : primes){
22 if(i%prime == 0){
23 isPrime = false;
24 break;
25 }
26 }
27 if(isPrime) primes.insert(i);
28 }
29
30 int pcount = primes.size(), npcount = n - pcount;
31 // cout << pcount << ", " << npcount << endl;
32 return (factorial(pcount) * factorial(npcount)) % modulo;
33 }
34};
Cost