Leetcode 1652. Defuse the Bomb
You have a bomb to defuse, and your time is running out! Your task is to find the code to defuse the bomb by following the instructions below:
code
of length n
.key
is required to defuse the bomb, where key
determines the behavior of the array transformation.You need to transform the array by creating a new array answer
of the same length where answer[i]
is the sum of the next k
elements (to the right if k
is positive, to the left if k
is negative) in the circular array. If k
is zero, then all elements in answer
should be zero.
code
array is [5,7,1,4]
and k = 3
, then the answer
array should be [12,10,16,13]
because:
answer[0] = 7 + 1 + 4 = 12
answer[1] = 1 + 4 + 5 = 10
(wrap around)answer[2] = 4 + 5 + 7 = 16
(wrap around)answer[3] = 5 + 7 + 1 = 13
(wrap around)k
be negative?code
always integers?code
array?code
array guaranteed to be circular?Let’s assume the array code
contains integers and is circular, the value of k
can be negative, and there are no other constraints on the values of the array elements.
answer
array of the same length as code
with zeros.code
array.k
is positive, negative, or zero:
k
is zero, answer[i]
will be zero for all elements.k
is positive, sum up the next k
elements to the right, considering the circular nature of the array.k
is negative, sum up the |k|
elements to the left.public class Solution {
public int[] decrypt(int[] code, int k) {
int n = code.length;
int[] answer = new int[n];
if (k == 0) return answer; // if k is 0, return array of all zeros
for (int i = 0; i < n; i++) {
int sum = 0;
if (k > 0) {
// Sum next k elements to the right
for (int j = 1; j <= k; j++) {
sum += code[(i + j) % n];
}
} else {
// Sum |k| elements to the left
for (int j = 1; j <= -k; j++) {
sum += code[(i - j + n) % n];
}
}
answer[i] = sum;
}
return answer;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] code = {5, 7, 1, 4};
int k = 3;
int[] result = sol.decrypt(code, k);
for (int num : result) {
System.out.print(num + " ");
}
}
}
The overall time complexity of this solution is O(n * | k | ). This is because for each element in code , we are potentially summing up to |k| elements, where n is the length of the code array and |k| is the absolute value of k . |
answer
array.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?