LeetCode 1652: Defuse the Bomb
Problem Description
Explanation
To solve this problem, we can iterate through each element in the circular array code
and calculate the sum based on the given key k
. We need to handle the cases where k
is positive, negative, or zero, and ensure that we wrap around the circular array appropriately.
-
For each element in the
code
array:- If
k > 0
, calculate the sum of the nextk
elements in a circular manner. - If
k < 0
, calculate the sum of the previousk
elements in a circular manner. - If
k == 0
, replace the current element with 0.
- If
-
We can use modular arithmetic to handle wrapping around the circular array. By taking the modulo of the index, we can ensure that we access elements within the valid range.
-
The time complexity of this solution is O(n) where n is the length of the
code
array. We iterate through the array once to calculate the decrypted code. -
The space complexity is O(n) as we use an additional array to store the decrypted code.
Solutions
class Solution {
public int[] decrypt(int[] code, int k) {
int n = code.length;
int[] decrypted = new int[n];
for (int i = 0; i < n; i++) {
int sum = 0;
if (k > 0) {
for (int j = 1; j <= k; j++) {
sum += code[(i + j) % n];
}
} else if (k < 0) {
for (int j = 1; j <= -k; j++) {
sum += code[(i - j + n) % n];
}
}
decrypted[i] = sum;
}
return decrypted;
}
}
Loading editor...