cool problem #1
problem:
A permuation of N numbers is a sequence where each number from 1 to N appears one time.
Given a permutation P and any arbitrary array A, operation f is defined as:
- for each index i(1 ≤ i ≤ N), new_A[i] = A[P[i]]
- A = newA
Now, if I give you a permutation of N numbers, can you tell me the minimum number of operations I have to make until I get back the original array? The answer might be big, so give the answer mod (10^9 + 7).
Example 1:
P = (3, 4, 1, 2)
index 1 maps to index 3 index 2 maps to index 4 index 3 maps to index 1 index 4 maps to index 2
I choose an arbitrary array of size N: A = (5, 6, 7, 8)
after operation 1, A becomes (7, 8, 5, 6) after operation 2, A becomes (5, 6, 7, 8)
the answer is 2 operations.
Example 2:
P = (4, 3, 1, 2)
A = (5, 6, 7, 8)
after operation 1: (8, 7, 5, 6) after operation 2: (6, 5, 8, 7) after operation 3: (7, 8, 6, 5) after operation 4: (5, 6, 7, 8)
the answer is 4 operations
Solution:
Have you ever heard that a permutation represents a bijection from a set onto itself? No? Well its true.
You don’t need to know that to solve the problem, but it might clue you into the fact that you are being given the edges of a graph. Indices are being mapped to other indices. Think of it as a directed graph where each vertex has an in-degree of 1 and an out-degree of 1.
Its should be obvious that the graph will have cycles: after enough operations that array always returns to its original state. You can also notice this by drawing the graph, which is what I did.
Say you have a cycle of length 3 and a cycle of length 2 in your permutation of n=5. In 3 operations, the 3-cycle elements will be in their original state, but the 2-cycle elements won’t.
When will they be at their original state at the same time?
The answer is lcm(2, 3) = 6.
Also, notice that the cycle lengths will all sum up to N.
This problem becomes complicated because of how fast the lcm will grow however. You can’t compute successive lcms because lcm(a, b, c) % d is not equal to lcm(a, lcm(b, c) % d) % d. That’s why you have to factor the cycle lengths into primes and store the max prime exponent seen.
lcm(6, 18) = 1^0 + 2^1 + 3^2
Steps:
- create index-to-index mapping array E such that if index i maps to index j, then E[i] = j
- initialize set to keep track of seen vertices as there’s no need to follow cycles that we’ve already seen. This also ensures that the prime factorization is only computed once per cycle.
- Go through each vertex, finding the length of the cycle it is a part of. And, add the seen vertices to the set.
- Afterwards compute the product of the primes. This is the LCM.
Notes: could have used unordered_map to store primes and their exponents. could have used sieve of eratosthenes for n = 10^5, to simplify prime factorization