3577. Count the Number of Computer Unlocking Permutations #2518
-
|
Topics: You are given an array There are The password for the computer labeled 0 is already decrypted and serves as the root. All other computers must be unlocked using it or another previously unlocked computer, following this information:
Find the number of permutations1 of Since the answer may be large, return it modulo Note that the password for the computer with label 0 is decrypted, and not the computer with the first position in the permutation. Example 1:
Example 2:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We are given an array complexity of length n. There are n locked computers labeled 0 to n-1, each with a unique password and a complexity value. The password for computer 0 is already decrypted (root). We can decrypt computer i using computer j if j < i and complexity[j] < complexity[i]. We must have already unlocked computer j. Approach:
Let's implement this solution in PHP: 3577. Count the Number of Computer Unlocking Permutations <?php
/**
* @param Integer[] $complexity
* @return Integer
*/
function countPermutations($complexity) {
$n = count($complexity);
$first = $complexity[0];
// Check if any other computer has complexity <= first
for ($i = 1; $i < $n; $i++) {
if ($complexity[$i] <= $first) {
return 0;
}
}
$mod = 1000000007;
$fact = 1;
// Compute (n-1)! modulo MOD
for ($i = 2; $i <= $n - 1; $i++) {
$fact = ($fact * $i) % $mod;
}
return $fact;
}
// Test cases
echo countPermutations([1,2,3]) . "\n"; // Output: 2
echo countPermutations([3,3,3,4,4,4]) . "\n"; // Output: 0
?>Explanation:
Complexity Analysis
|
Beta Was this translation helpful? Give feedback.
We are given an array complexity of length n. There are n locked computers labeled 0 to n-1, each with a unique password and a complexity value. The password for computer 0 is already decrypted (root). We can decrypt computer i using computer j if j < i and complexity[j] < complexity[i]. We must have already unlocked computer j.
Approach: