1652. Defuse the Bomb #847
-
Topics: You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array To decrypt the code, you must replace every number. All the numbers are replaced simultaneously.
As Given the circular array Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can implement a function that iterates over the The general approach will be as follows:
The circular nature of the array means that for indices that exceed the bounds of the array, you can use modulo ( Let's implement this solution in PHP: 1652. Defuse the Bomb <?php
/**
* @param Integer[] $code
* @param Integer $k
* @return Integer[]
*/
function decrypt($code, $k) {
$n = count($code);
$result = array_fill(0, $n, 0);
if ($k === 0) {
return $result; // If k is 0, all elements become 0.
}
for ($i = 0; $i < $n; $i++) {
$sum = 0;
// Determine direction and range of elements to sum
if ($k > 0) {
for ($j = 1; $j <= $k; $j++) {
$sum += $code[($i + $j) % $n]; // Wrap around using modulo
}
} else { // k < 0
for ($j = 1; $j <= abs($k); $j++) {
$sum += $code[($i - $j + $n) % $n]; // Wrap around backward using modulo
}
}
$result[$i] = $sum;
}
return $result;
}
// Example Usage
$code1 = [5, 7, 1, 4];
$k1 = 3;
print_r(decrypt($code1, $k1)); // Output: [12, 10, 16, 13]
$code2 = [1, 2, 3, 4];
$k2 = 0;
print_r(decrypt($code2, $k2)); // Output: [0, 0, 0, 0]
$code3 = [2, 4, 9, 3];
$k3 = -2;
print_r(decrypt($code3, $k3)); // Output: [12, 5, 6, 13]
?> Explanation:
Outputs:The provided examples match the expected results. Let me know if you need further explanation or optimizations! |
Beta Was this translation helpful? Give feedback.
We can implement a function that iterates over the
code
array and computes the sum of the appropriate numbers based on the value ofk
.The general approach will be as follows:
k == 0
, replace all elements with 0.k > 0
, replace each element with the sum of the nextk
elements in the circular array.k < 0
, replace each element with the sum of the previousk
elements in the circular array.The circular nature of the array means that for indices that exceed the bounds of the array, you can use modulo (
%
) to "wrap around" the array.Let's implement this solution in PHP: 1652. Defuse the Bomb